Вопрос

I have 2 models, Sound and Tag:

<?php

class Sound extends Eloquent{

    protected $table = 'sounds';

    protected $guarded = array('id');

    public function tags()
    {
        return $this->belongsToMany('Tag');
    }
} 

<?php

class Tag extends \Eloquent {

    protected $table = 'tags';

    protected $guarded = array('id');

    public function sounds()
    {
        return $this->belongsToMany('Sound');
    }
}

In the controller I do lazy loading and it works as expected; the sounds are fetched and each of them has tags attached. The code below:

$sounds = Sound::with(array('tags'))->get();

I now want to filter the sounds by a tag_id (get only the sounds that have a particular tag attached) and I'm not sure if it's possible in Eloquent.

I tried eager load constraints but these would only specify the condition based on which a tag is attached to a sound or not, and not actually filter the sounds.

Should I use the query builder instead?

Thank you.

Это было полезно?

Решение

try this code

$sounds = Sound::whereHas('tags', function($q) use($tag_id)
{
    $q->where('tags.id', '=', $tag_id);

})->get();

so you only get sounds with a certain tag.

Другие советы

angorus's answer is perfectly fine. Just some additional information on this: If you need functions like this more often, it can be helpful to put them in a query scope within your model.

<?php

class Sound extends Eloquent{

  //....

  public function scopeHasTag($query, $tag_id)
  {
    return $query->whereHas('tags', function($q) use ($tag_id)
    {
      $q->where('tags.id', '=', $tag_id);
    });
  }
} 

Then in the controller, to only get those Sounds that have a certain tag associated you can do something like:

$sounds = Sound::with('tags')->hasTag($tag_id)->get();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top