php - 在 Laravel 4 中如何查询 ManyToMany 关系?

标签 php orm laravel laravel-4 eloquent

在 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/

相关文章:

php - Laravel 4, ->withInput(); = undefined offset : 0

javascript - 如何使用 PHP 获取被 javascript 隐藏的 URL 的内容

php - xampp 控制面板 Apache 端口未打开

java - Wildfly - 如何启用事务以启用延迟加载

php - 尝试使用 strtotime 将 mysql 时间戳转换为时间

c# - Nhibernate 的 Get 和 Load 方法不支持 session 过滤器?

c# - 亚音速 ORM 体验

php - Laravel : How to store json format data in database?

php - Laravel Eloquent 的基本选择不起作用

php - 使用集合值获取 Laravel 集合的项目