Php Laravel:使用雄辩的belongsto,从两个表中获取数据?

Php Laravel:使用雄辩的belongsto,从两个表中获取数据?,php,database,laravel,eloquent,Php,Database,Laravel,Eloquent,在控制器中,我只想从父级传递一个带有specifies列的变量。现在,我正在使用 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.titl

在控制器中,我只想从父级传递一个带有specifies列的变量。现在,我正在使用

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();
我的问题是

1.使用Belongsto有没有更好的方法

2.如果可以,对Hasmany是否也一样

这是我的桌子结构

用户

id | name
1  | 'John'
设计

id | user_id |  title
1  |    1    | 'Chill'  
2  |    1    |  'Mad'
产品

id | design_id | price
1  |     1     |  20  
2  |     1     |  30
模型应该是这样的

产品属于设计
设计属于用户

向用户添加一种方法,如用户所拥有的设计

id | name
1  | 'John'
public function designs(){
    $this->hasMany('Design');
}
对于设计模型,添加以下方法

public function user(){
    $this->belongsTo('User');
}

public function products(){
    $this->hasMany('Product');
}
适用于您的产品型号

public function design(){
    $this->belongsTo('Design');
}
这些将建立关系,允许您在模型上加载数据

可以这样做

$variable = Product::with('designs')->find(1); //This will load the product with the related designs
如果希望所有设计和属于设计的用户执行以下操作:

$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.
要访问属性,请使用以下命令:

$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.
显示信息的示例

@foreach ($variable->designs as $design)
    {{ $design->user->username }}
@endforeach

请注意:我还没有测试这段代码。

差不多了!如果我也想要一个相关的用户,你能这样做吗?@Johny编辑以显示如何访问信息。为了获得相关用户,还可以使用Product::with('designs','design.user')->find(1);