2

I have 3 models Content, ContentType, and Taxonomy. Their relationships are set up like this:

Content model:

public function contentType()
{
    return $this->belongsTo('App\ContentType', 'ct_id');
}
public function taxonomies()
{
    return $this->morphToMany('App\Taxonomy', 'taxonomical');
}

ContentType model:

public function contents()
{
    return $this->hasMany('App\Content', 'ct_id', 'id');
}

Taxonomy:

public function contents()
{
    return $this->morphedByMany('App\Content', 'taxonomical');
}

I am getting an array with taxonomies that I should use to filter the contents, the array could look like this one:

$taxonomiesArray =  ["Administrasjon", "Oslo", "Bane"]

With this kind of array I should make a query, where I would get only contents, that have all the taxonomies from that array, and are of contentType where column name is intranet-post, basically something like this:

$intranetTypePostID = ContentType::where('name', 'intranet-post')->pluck('id');
$contents = Content::where('ct_id', $contentType->id)->with(['taxonomies' => function($q) use ($userTaxonomies){
      $q->whereIn('slug', $userTaxonomies);
    }])->get();

But, how can I get only contents that have all the taxonomies that have the same slug as the values from the array $taxonomiesArray?

Leff
  • 1,968
  • 24
  • 97
  • 201
  • Look into [Constraining Eager Loads](https://laravel.com/docs/5.5/eloquent-relationships#constraining-eager-loads) – ljubadr Oct 25 '17 at 16:52
  • to pass `$taxonomiesArray` to callback use `...::with(['taxonomies' => function ($query) use ($taxonomiesArray) { ...` – ljubadr Oct 25 '17 at 16:55
  • yes, I know that, but how can I than get only the contents that have all the taxonomies from the array, if I pass the array like that and use whereIn, I will get all the contents that have at least one taxonomy that is contained in the array $taxonomiesArray, and that is not what I need – Leff Oct 26 '17 at 15:51
  • To get **where in** to match **all**, you could use [Matching all values in IN clause](https://stackoverflow.com/questions/11636061/matching-all-values-in-in-clause/11636084#11636084) in your `::with(`. I don't have time to test this out and to write an answer. – ljubadr Oct 26 '17 at 16:55

0 Answers0