Home > Net >  guery in bitween 3 table by relation
guery in bitween 3 table by relation

Time:09-02

I have these relations

user has many products

product has many files

I want products that : in user table status field is 1 and in file table status field is 1

CodePudding user response:

If you have defined relationships in eloquent model, then that is the query you need:

$products = Product::whereRelation('user', 'status', '1')->
whereRelation('files', 'status', '1')->get();

Relationships

In Product model

public function user(){
    $this->belongsTo(User::class);
}

public function files(){
    $this->hasMany(File::class);
}

CodePudding user response:

You may use the whereHas method if you prefer

First set the relations in Product model like this:

public function user(){
    $this->belongsTo(User::class);
}

public function files(){
    $this->hasMany(File::class);
}

And then you can mount your query using the whereHas like this:

$products = Product::whereHas('user', function (Builder $query) {
            $query->where('status', 1);
        })->whereHas('files', function (Builder $query) {
            $query->where('status', 1);
        })->get();

And finally, if you're using php >= 7.4 you can do the trick using arrow functions, which makes it cleaner:

$products = 
  Product::whereHas('user',  fn (Builder $query) => $query->where('status', 1))
         ->whereHas('files', fn (Builder $query) => $query->where('status', 1))->get();
  • Related