Dev
Dev

Reputation: 1073

How to add condition in connection tables?

I have two tables: Users and Images.

So, a user can have some images.

For this relationship I have additional function in model User:

public function images()
{
    return $this->hasMany('App\Images', 'idElement', 'id');
}

And in controller I have:

$users = Users::where('id', $id)->with("images")->get();

How can I add additional condition in controller for images table that will be "where images.type = 1"?

Now this tables are connected only by primary keys, but I need to set a new condition yet.

Upvotes: 3

Views: 1819

Answers (2)

Tim Lewis
Tim Lewis

Reputation: 29268

For something like this, where you want to scope down a subset of images based on their type, you can add another method called something like public function scopedImages() and define it as such:

public function scopedImages() {
    return $this->hasMany('App\Images', 'idElement', 'id')->where("images.type", "=", 1);
}

In your controller, you would access this function the same as you would the images() function on User:

$users = Users::where('id', $id)->with(["scopedImages"])->get();

Keep the function images() as well, so if you need to find all images attached to a User, but adding additional functions like this gives you flexibility on what you want to return and when.

Upvotes: 2

Jose Rojas
Jose Rojas

Reputation: 3520

You can filter your images with callback function, try this:

$users = Users::where('id', $id)->with(["images" => function ($query){
    $query->where('type', 1);   
}])->get();

Upvotes: 5

Related Questions