Filter results with Manytomany relationship in the Aravel

Asked

Viewed 462 times

1

I have 2 tables where there is a relationship, client and content using a pivot table contents_clients, when selecting the contents of the "X" client I can know which contents belong to it, but I can’t apply a filter referencing a table column content

$client = Client::find($client_id)->contents;
// Retorna um array de collection com os conteudos

all: [
   App\Content {#795
     id: "76",
     title: "Teste Client 1",
     content: "TESTE",
     client_alteration: null,
     target: "2",
     scheduled_to: "2016-08-30 00:00:00",
     status: "2",
     created_at: "2016-08-29 14:27:34",
     updated_at: "2016-08-29 14:27:34",
     pivot: Illuminate\Database\Eloquent\Relations\Pivot {#794
       client_id: "1",
       content_id: "76",
     },
   },............

How do I apply a filter and select the status = 2 ? I’ve tried to: $client = Client::find($client_id)->contents->where('status', 2)->get(); and I get; PHP warning: Missing argument 1 for Illuminate\Support\Collection::get()

  • For this to work contents->where I believe the Contents has to be called as a method Client::find($client_id)->contents()->where('status', 2)->get();

1 answer

1

Using that way you’re firing the Where method of Collection, and not of query Builder. You could try chaining the Where method right after receiving a relationship, but this would result in a collection of contents and not of clients, thus:

$contents = Client::find($id)->contents()->where('contents.status', 2)->get();

For these situations, you can change the query of an Eager loading, thus:

$clients = Client::with(
    [
        'contents' => function ($query) {
            $query->where('contents.status', 2);
        }
    ]
)->get();

Note: Version of Laravel 5.3.

Browser other questions tagged

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