在 Laravel 4 中我有以下表格
- items table
--- id
--- name
- tags table
--- id
--- name
- item_tag
--- id
--- tag_id
--- item_id
--- created_at
--- updated_at
class Item extends Eloquent {
public function tags()
{
return $this->belongsToMany('Tag');
}
}
class Tag extends Eloquent {
public function items()
{
return $this->hasMany('Item');
}
}
我的问题:
我想获取所有具有以下两个标签“foo”和“bar”的项目?只有具有两个标签的项目才应该退回!?
更新
我已经尝试了下面的方法,但它对我不起作用,我感觉问题出在“->having”子句上,但我无法正确处理,
假设标签“foo”的 ID 为 1,“bar”的 ID 为 2
class Item extends Eloquent {
protected $table = 'items';
public function tags()
{
return $this->belongsToMany('Tag');
}
public static function withTags()
{
return static::leftJoin(
'item_tag',
'items.id', '=', 'item_tag.item_id'
)
->whereIn('item_tag.tag_id', array(1, 2))
->groupBy('items.id')
->having('count(*)', '=',2)
;
}
}
并运行它
#routes.php
Route::get('/', function()
{
return Item::withTags()->get();
});
它应该返回带有标签 1 和 2 的所有项目,但它没有返回任何东西!
有什么帮助吗?
最佳答案
终于找到答案了!
使用“havingRaw”将解决问题
“列表”还为我们提供了标签表中标签的 ID
注意:“havingRaw”仅在 Laravel 4 -beta 4- 或更高版本中可用
class Item extends Eloquent {
protected $table = 'items';
public function tags()
{
return $this->belongsToMany('Tag');
}
public static function withTags($tags = array())
{
$count = count($tags);
return static::leftjoin('item_tag', 'items.id', '=', 'item_tag.item_id')
->whereIn('item_tag.tag_id', Tag::whereIn('name', $tags)->lists('id'))
->groupBy('item_tag.item_id')
->havingRaw('count(*)='.$count)
;
}
}
并运行它
return Item::withTags(['foo','bar'])->get();
更新:重要提示
当您看到上面代码的输出时,您会注意到 item->id 不包含 items.id!,而是包含 tags.id,这是因为使用“joins”会导致歧义, 要解决这个问题,您必须添加以下选择语句
->select('items.id as id','items.name as name')
关于php - 在 Laravel 4 中如何查询 ManyToMany 关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15453921/