Laravel 5.5无法使用belongsTo获取选定的列数据

问题描述 投票:1回答:3

我有两个与Eloquent Laravel相关的模型(UserUsersDetails)。

用“SelDetails”模型“用户”反映

public function SelDetails {
    return $this->belongsTo('App\UsersDetails', 'users_id');
}

我想从SelDetails只获得两列'created_by_id','created_by_name'

UserController的

$users = User::with(['SelDetails' => function($query){
        $query->select(['created_by_id', 'created_by_name']);
    }])
    ->where('is_active', '=', 0)
    ->orderBy('id', 'desc')
    ->get();

我从User获取数据但在SelDetails中空白

[relations:protected] => Array
(
     [SelDetails] => 
)

请指正。

laravel eloquent laravel-5.5
3个回答
1
投票

各位朋友,感谢你们对这个问题的宝贵回应。我通过以下方式获得了解决方案。

“用户”模型中的更改与“SelDetails”的关系

public function SelDetails {
    #return $this->belongsTo('App\UsersDetails', 'users_id');// the old one
    return $this->hasOne('App\UsersDetails', 'users_id');
}

“UserController”中的更改

$users = User::with('SelDetails')->where('is_active', '=', 0)->orderBy('id', 'desc')->get();

这就是我所做的改变并得到了结果

enter image description here

谢谢


0
投票

我可能错了,但它可能是select中的数组,试试

$query->select('created_by_id', 'created_by_name');

0
投票

你尝试过类似的东西吗?

来自$users = App\Book::with('author:id,name')->get();the documentation?在你的情况下,它应该看起来像:

User::with('SelDetails:created_by_id,created_by_name')
    ->where('is_active', '=', 0)
    ->orderBy('id', 'desc')
    ->get();

with()方法可以采用字符串(或由字符串填充的数组),例如。 relationName:column1,column2

© www.soinside.com 2019 - 2024. All rights reserved.