Laravel Eloquent 都与关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21092264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent all with relationship
提问by Kolesar
How can I get all data from my tables with relationship in Laravel?
如何从 Laravel 中具有关系的表中获取所有数据?
So, I have table like:
所以,我有这样的表:
*users*
id
username
password
...
*address*
id
address
user_id
...
If I call my eloquent model with Address::all() I get response with user_id, and I want to make relationships for getting username.
如果我用 Address::all() 调用我的 eloquent 模型,我会得到 user_id 的响应,并且我想建立关系以获取用户名。
I try to add:
我尝试添加:
public function users(){
return $this->belongsTo('Users', 'user_id');
}
And call with Address::with('users')->get()
, but response is empty.
并调用Address::with('users')->get()
,但响应为空。
回答by berrberr
Is your user class called Users
or User
? Unless you override it, the default way that Eloquent deals with names can be found in the docs (source):
你的用户类是叫Users
还是User
?除非您覆盖它,否则 Eloquent 处理名称的默认方式可以在文档(源)中找到:
Note that we did not tell Eloquent which table to use for our User model. The lower-case, plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the User model stores records in the users table. You may specify a custom table by defining a table property on your model
请注意,我们没有告诉 Eloquent 将哪个表用于我们的 User 模型。除非明确指定另一个名称,否则类的小写复数名称将用作表名。因此,在这种情况下,Eloquent 将假设 User 模型将记录存储在 users 表中。您可以通过在模型上定义表属性来指定自定义表
So I believe if you change your code in the Address model to:
所以我相信如果你将 Address 模型中的代码更改为:
public function users(){
return $this->belongsTo('User', 'user_id');
}
it will work since we have changed Users
to User
它将起作用,因为我们已更改Users
为User
回答by xSkArx
You need to change
你需要改变
public function users(){
return $this->belongsTo('Users', 'user_id');
}
to
到
public function users(){
return $this->hasOne(Users::class, 'user_id');
}
or
或者
public function users(){
return $this->hasMany(Users::class, 'user_id');
}
回答by Bilal Maqsood
Alternative way!
替代方式!
class Users extends Model {
//override table
protected $table = 'users';
protected $primaryKey = 'id';
//Your other code here
}
and in Address Model add like this
并在地址模型中添加这样
public function users(){
return $this->belongsTo('App\Users', 'user_id');
}