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

时间:2018-09-16 20:25:06

标签: laravel eloquent laravel-5.5

与雄辩的Laravel有2个模型(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] => 
)

请纠正我。

3 个答案:

答案 0 :(得分: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

谢谢

答案 1 :(得分:0)

您尝试过类似的事情

是来自the documentation

<a class="backgroundbutton">hover over me</a>吗? 在您的情况下,其外观应为:

$users = App\Book::with('author:id,name')->get();

User::with('SelDetails:created_by_id,created_by_name') ->where('is_active', '=', 0) ->orderBy('id', 'desc') ->get(); 方法可以采用字符串(或由字符串填充的数组),例如。 with()

答案 2 :(得分:0)

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

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