dongyi6195 2015-10-27 10:46
浏览 182

如何使用透视表来获取数据,使用laravel 4中的pivot上的where条件

How can I fetch data with belongsToMany relation models.

Table tags
  - id
  - name
  ...

Table photo_entries
  - id
  ...

Table photo_entry_tag
  - id
  - tag_id
  - photo_entry_id

Tag.php

public function photo_entry()
{
    return $this->belongsToMany('PhotoEntry');
}

PhotoEntry.php

public function tags()
{
    return $this->belongsToMany('Tag');
}

Now I need to fetch photo entries from photo_entries table with their tags where tag_id=1.

I have tried this:

$photos = PhotoEntry::orderBy('votes', 'desc')->with(array('tags' => function($query)
{
   $query->where('tag_id', 1); 
}))->paginate(50);

But its not giving me the proper result, its returning all photos. I am not getting what is the issue.

Can any one please help me.

  • 写回答

1条回答 默认 最新

  • douyong1886 2015-10-30 13:18
    关注

    You need to select all records form photo_entries table that has a relation in photo_entry_tag table so to do that your query should be like this

    $tag_id = 1;
    $query = "SELECT * FROM `photo_entries` WHERE `id` IN (SELECT `photo_entry_id` FROM `photo_entry_tag` WHERE `tag_id` = {$tag_id})";
    

    Also the equivalence code in eloquent will be like the code below

    $tag_id = 1;
    $photos = PhotoEntry::whereIn('id', function($query) use ($tag_id) {
        $query->select('photo_entry_id')->from('photo_entry_tag')->whereTagId($tag_id
    );
    })->get();
    

    Also you can add orderBy('votes', 'desc') just before get() to sort the result

    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探