简体   繁体   English

Laravel 5.2雄辩的hasOne关系不起作用

[英]Laravel 5.2 Eloquent hasOne relationship doesn't work

I have relationship in my chat model 我的聊天模型中有关系

public function user() {
    return $this->hasOne(User::class,'id','writers_id');
}

And want to use it in my controller. 并想在我的控制器中使用它。 I tryed many ways, but no one worked. 我尝试了很多方法,但是没有人起作用。 Just giving last try example (result - blank page). 仅给出最后的尝试示例(结果-空白页)。

print_r($chat = Chat::where('id', 1)->first()->user);

Can anyone help me? 谁能帮我? Thanks! 谢谢! I don't really understand that Eloquent, used simple DB query maker before, however someone said that I should do every database stuff in model. 我不太了解Eloquent以前使用过简单的数据库查询器,但是有人说我应该在模型中处理所有数据库工作。 Is it correct? 这是正确的吗? Sorry about my poor English! 对不起,我的英语不好!

First as mentioned by @Vohuman 首先是@Vohuman提到的

return $this->hasOne('App\User', 'id', 'writers_id');

And when using it: 使用时:

Chat::where('id', 1)->first()->user()->first()->attribute

Look here: https://laravel.com/docs/master/eloquent-relationships#one-to-one 在这里查看: https : //laravel.com/docs/master/eloquent-relationships#one-to-one

In App\\Chat.php : App\\Chat.php

public function writer()
{
    return $this->hasOne('App\User','id','writers_id');
}

to define the relation. 定义关系。 Then in whatever controller: 然后在任何控制器中:

At top: 在顶部:

use App\User;

and inside the method: 在方法内部:

$writer = User::find($user_id)->writer;

to debug it add one line in front of the above line. 要对其进行调试,请在上述行的前面添加一行。

dd($user_id,User::find($user_id),$writer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM