Consultation with eloquent relationship

Asked

Viewed 650 times

0

I am hitting myself here with a simple query on Laravel, I want to make a query on the client table and bring the customer’s address together.

Note: Whenever I try it brings the address id and not the client id

class Address extends Model
{
    protected $fillable = [
        'street',
        'number',
        'neighborhood',
        'complement',
        'reference',
        'zip_code',
        'phone',
        'cel_phone',
        'city',
        'state',
    ];

    public function client()
    {
        return $this->hasMany(Client::class);
    }
}

class Client extends Model
{
    protected $fillable = [
        'name',
        'email',
        'cpf',
        'rg',
        'address_id',
    ];

    public function address()
    {
        return $this->belongsTo(Address::class);
    }
}

Example from SQL:

SELECT * FROM 'clients' as A 
     INNER JOIN 'addresses' as B on a.address_id = b.id 
        WHERE a.id =" $id;
  • How are you doing? If you did so Cliente::with('address')->get()? Or didn’t try anything?

  • What is the type of relationship between Client and Address? is 1 client for many addresses? I did not understand well which relation you want to use, first defines which relationship exists between these two tables !

  • 1

    Each customer has only one address, but there is the possibility of more than one customer living at the same address! You would be right this way?

1 answer

0


Correcting your relationship first:

class Address extends Model
{
    protected $fillable = [
        'street',
        'number',
        'neighborhood',
        'complement',
        'reference',
        'zip_code',
        'phone',
        'cel_phone',
        'city',
        'state',
    ];

    public function client()
    {
        return $this->hasMany(Client::class, 'address_id', 'id');
    }
}

class Client extends Model
{
    protected $fillable = [
        'name',
        'email',
        'cpf',
        'rg',
        'address_id',
    ];

    public function address()
    {
        return $this->hasOne(Address::class, 'id', 'address_id');
    }
}

After fixing you go into the controller and call the clients model.

Client::with('address')->get(); //Para pegar todos clientes com seus endereços

Client::with('address')->whereHas('address', function($query) use ($request){
   $query->where('city', $request->city);
})->get(); // Pegar todos clientes com where na tabela address de city você pode usar qualquer campo que desejar dentro da function do whereHas

Client::all() // Pegar todos clientes com todos relacionamento

See which one helps you and be happy.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.