【问题标题】:Laravel: selecting with conditions from Many-to-many relationshipsLaravel:从多对多关系中选择条件
【发布时间】:2013-11-13 18:15:19
【问题描述】:

我的帖子和主题有一个多对多的 laravel 关系:

  • 帖子属于多个主题
  • 主题属于许多帖子

我想从某个主题获取id > 10的帖子

以下代码将为我获取某个主题的所有帖子:

$topic = Topic::where('id',$topic_id)->get()->first();
$posts= $topic->post;

现在如何获取 id > 10 的帖子?

型号:

class Topic extends Eloquent{

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

class Post extends Eloquent{

    public function topic()
    {
        return $this->belongsToMany('Topic');
    }       
}

【问题讨论】:

    标签: laravel many-to-many


    【解决方案1】:

    你应该这样做

    $topic = Topic::find($topic_id);   
    $posts= $topic->posts()->where('id','>',10)->get();  
    

    $posts = Topic::find($topic_id)->posts()->where('id','>',10)->get(); 
    

    希望有帮助

    【讨论】:

      【解决方案2】:

      如果要将Where 子句应用于belongsToMany

      这里是where条件

      $permissions = Role::with('getRolePermissions')->where('id', '=', Auth::guard('admin')->user()->id)->get()->toArray();
      

      在这个 URL 中getRolePermissions 是模型函数,在里面我使用了多对多关系

      public function getRolePermissions() {
              return $this->belongsToMany('App\Permission', 'permission_role');        
      
          }
      

      【讨论】:

        【解决方案3】:

        像这样:

        Topic::with(array('posts' => function($q)
        {
            $q->where('id', '>', 10);
        
        }))->where('id', $id)->first();
        

        【讨论】:

        • 抱歉,我将 id 替换为主题 id,但现在我收到此错误:{"error":{"type":"BadMethodCallException","message":"Call to undefined method Illuminate \\Database\\Query\\Builder::posts()","file":"C:\\wamp\\www\\-\\vendor\\laravel\\framework\\src\\Illuminate\\Database \\Query\\Builder.php","line":1657}}
        • 它正在调用你创建的方法。你的是post(),他的是posts()posts() 更有意义,所以我将Topic 模型中的函数名称更改为posts()
        猜你喜欢
        • 1970-01-01
        • 2014-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        相关资源
        最近更新 更多