Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Laravel中选择hasOne_Laravel_Laravel 8 - Fatal编程技术网

在Laravel中选择hasOne

在Laravel中选择hasOne,laravel,laravel-8,Laravel,Laravel 8,我有三种型号 Posts Users UserImages 在我的帖子里 public function user() { return $this->belongsTo(new User)->with('avatar'); } 在用户中,我有 public function avatar() { return $this->hasOne(UserImage::class)->where('type', 1); //type 1 is avatar;

我有三种型号

Posts
Users
UserImages
在我的帖子里

public function user() {
    return $this->belongsTo(new User)->with('avatar');
}
在用户中,我有

public function avatar() {
    return $this->hasOne(UserImage::class)->where('type', 1); //type 1 is avatar;
}
我从Posts controller打电话,我有下面的屏幕截图:

$posts = $this->model::select('*')->with('user')->get();

它返回的信息太多。我想选择像thí这样的东西


hasOne和belongsTo是否可行?

您可以加入“急切加载”查询以获得所需的结果:

$posts = $this->model::select('*')->with(['user'=>function($query) {
            $query->join('avatars', 'avatars.user_id', 'users.id')
                ->select(['users.id', 'users.name', 'users.userName', 'avatars.images_url']);
        }])->get();
要使用“化身”关系,您可以使用多个角色:

 $posts = $this->model::select('*')->with(['user'=>function($query) {
                $query->select(['users.id', 'users.name', 'users.userName'])
                ->with(['avatar'=>function($query){
                    $query->select(['user_id','images_url']);
                }]);

您可以加入渴望加载查询以获得所需的结果:

$posts = $this->model::select('*')->with(['user'=>function($query) {
            $query->join('avatars', 'avatars.user_id', 'users.id')
                ->select(['users.id', 'users.name', 'users.userName', 'avatars.images_url']);
        }])->get();
要使用“化身”关系,您可以使用多个角色:

 $posts = $this->model::select('*')->with(['user'=>function($query) {
                $query->select(['users.id', 'users.name', 'users.userName'])
                ->with(['avatar'=>function($query){
                    $query->select(['user_id','images_url']);
                }]);

谢谢你的提问。这很好,但我在用户模型中定义了hasOne(UserImage::class)。有没有办法做到这一点,而不是使用连接与查询生成器?如果您的答案是唯一的方式,那么Laravel helper在关系中没有帮助?请参阅更新的answerI added condition->where('avatars.type',1),作为上面的连接方法,如果用户没有化身,它将为用户返回null?是的,如果您不想这样做,您可以使用leftJoin而不是joinThank谢谢您的查询。这很好,但我在用户模型中定义了hasOne(UserImage::class)。有没有办法做到这一点,而不是使用连接与查询生成器?如果只有一种方式作为您的答案,那么Laravel helper在关系中没有帮助?请参阅更新的answerI added condition->where('avatars.type',1),作为上面的连接方法,如果用户没有化身,它将为用户返回null?是的,如果您不想这样做,您可以使用leftJoin而不是join