Laravel 4.1-基于数据透视表值的雄辩惰性加载和过滤结果
我有两种型号,Laravel 4.1-基于数据透视表值的雄辩惰性加载和过滤结果,laravel,laravel-4,eloquent,pivot-table,has-and-belongs-to-many,Laravel,Laravel 4,Eloquent,Pivot Table,Has And Belongs To Many,我有两种型号,声音和标签: <?php class Sound extends Eloquent{ protected $table = 'sounds'; protected $guarded = array('id'); public function tags() { return $this->belongsToMany('Tag'); } } 现在我想通过一个标签id来过滤声音(只获取附加了特定标签的声音)
声音
和标签
:
<?php
class Sound extends Eloquent{
protected $table = 'sounds';
protected $guarded = array('id');
public function tags()
{
return $this->belongsToMany('Tag');
}
}
现在我想通过一个标签id
来过滤声音(只获取附加了特定标签的声音),我不确定这是否可能在雄辩中实现
我尝试了快速加载约束,但这些约束只指定了将标记
附加到声音
的条件,而不是实际过滤声音
我应该改用查询生成器吗
谢谢。试试这段代码
$sounds = Sound::whereHas('tags', function($q) use($tag_id)
{
$q->where('tags.id', '=', $tag_id);
})->get();
所以你只能听到带有特定标签的声音。安哥罗斯的回答很好。关于这一点,请提供一些补充信息:
如果您更经常需要这样的函数,那么将它们放在模型中的查询范围内会很有帮助
<?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);
});
}
}
$sounds = Sound::whereHas('tags', function($q) use($tag_id)
{
$q->where('tags.id', '=', $tag_id);
})->get();
<?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);
});
}
}
$sounds = Sound::with('tags')->hasTag($tag_id)->get();