简体   繁体   中英

Laravel: use Eloquent belongsto , get data from both tables?

In Controller, I would like to pass the only one variable with specifies column from parent in it. Now,I'm using

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?

2.If can do, Is it work the same with 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

Product belongsto Design , Design belongsto User

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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