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');
}
}
私の質問:
次の 2 つのタグ「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 を持つすべてのアイテムを返す必要がありますが、何も返されません!
助けはありますか?