【发布时间】:2013-03-05 10:30:05
【问题描述】:
在 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 的所有项目,但是它没有返回任何东西!
有什么帮助吗?
【问题讨论】:
-
您可以在页面底部看到 config/application.php 中设置 profiler = true 后执行的 sql 查询。之后,如果您可以共享 sql quaries,我们可以更有效地为您提供帮助。
标签: php orm laravel laravel-4 eloquent