代码之家  ›  专栏  ›  技术社区  ›  Rafay Hassan

为什么在Laravel 5.7中,Select不在雄辩中工作?

  •  0
  • Rafay Hassan  · 技术社区  · 7 年前

    以下代码工作正常:

    Post::with(['user'])
        ->get();
    

    但是当我尝试使用select过滤它时,它在用户关系中返回空值。

    Post::with(['user' => function($query){
        $query->select('name');
    }])
    ->select('id', 'slug', 'title', 'body', 'created_at')
    ->get();
    

    用户模型内部的关系:

    public function posts()
    {
        return $this->hasMany('App\Post');
    }
    

    岗位模型内部关系:

    public function user()
    {
       return $this->belongsTo('App\User', 'user_id');
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Jonas Staudenmeir    7 年前

    您必须选择外键( posts.user_id )和所有者密钥( users.id ):

    Post::with(['user' => function($query){
        $query->select('id', 'name');
    }])
    ->select('id', 'slug', 'title', 'body', 'created_at', 'user_id')
    ->get();
    

    您也可以使用这个较短的版本:

    Post::with('user:id,name')
        ->select('id', 'slug', 'title', 'body', 'created_at', 'user_id')
        ->get();
    
        2
  •  0
  •   Justin J    7 年前

    你能处理一下吗

    DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
    
    推荐文章