Laravel:使用 Eloquent ownto ,从两个表中获取数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26656184/
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: use Eloquent belongsto , get data from both tables?
提问by Johny
In Controller, I would like to pass the only one variable with specifies column from parent in it. Now,I'm using
在 Controller 中,我想传递唯一一个带有父级指定列的变量。现在,我正在使用
View::make('store.product')->with('products', Product::find($id)
->join('design','product.design_id','=','design.id')
->join('user','design.user_id','=','user.id')
->select('user.name','design.title','product.price')
->get();
My question is
我的问题是
1.Is there a better way to do this by using Belongsto?
1. 使用 Belongsto 有没有更好的方法来做到这一点?
2.If can do, Is it work the same with Hasmany?
2.如果可以,和Hasmany一样吗?
This is my table structure.
这是我的表结构。
User
用户
id | name
1 | 'John'
Design
设计
id | user_id | title
1 | 1 | 'Chill'
2 | 1 | 'Mad'
Product
产品
id | design_id | price
1 | 1 | 20
2 | 1 | 30
And Model be like this
和模型是这样的
Productbelongsto Design, Designbelongsto User
产品属于设计, 设计属于用户
回答by Matt Burrow
Add a method to your Users like so for your designs that the user has;
为您的用户添加一个方法,例如为用户拥有的设计;
public function designs(){
$this->hasMany('Design');
}
For the designs model add the following methods;
对于设计模型,添加以下方法;
public function user(){
$this->belongsTo('User');
}
public function products(){
$this->hasMany('Product');
}
For your products model
对于您的产品型号
public function design(){
$this->belongsTo('Design');
}
These will set up the relationship allowing you to eager load the data on your models.
这些将建立关系,允许您在模型上急切加载数据。
This can be done like so;
这可以像这样完成;
$variable = Product::with('designs')->find(1); //This will load the product with the related designs
If you want all the designs and the users that belong to the designs do the following;
如果您想要所有设计和属于设计的用户,请执行以下操作;
$variable = Product::with('designs', 'design.user')->find(1); //This will load the designs that relate to the Product and include the user that that design belongs to on the Design model.
To access the properties use the following;
要访问属性,请使用以下内容;
$variable->designs //This will return a collection of all the designs.
$variable->designs->first()->user //This will return the user model that the design belongs to.
An example of displaying the information;
显示信息的示例;
@foreach ($variable->designs as $design)
{{ $design->user->username }}
@endforeach
Please note: i have not tested this code.
请注意:我尚未测试此代码。