首页 文章

Laravel:从多对多关系中选择条件

提问于
浏览
0

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

  • 帖子属于许多主题

  • 主题属于许多帖子

我想从 a certain topic 获取 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');
    }       
}

3 回答

  • 1

    像这样:

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

    如果要将 Where 子句应用于 belongsToMany

    这是条件

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

    在这个URL中 getRolePermissions 是模型函数,在其中我使用了Many To Many关系

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

    你应该这样做

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

    要么

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

    希望这个帮助

相关问题