Laravel: use Eloquent to get data from both tables?
In the controller, I would like to pass only one variable with the column specified from the parent in it. Now I am 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
1. Is there a better way to do this using Belongsto?
2.If can do it, does it work with Hasmani?
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 the model will be like this
Product belongs to Design , Design belongs to User
source to share
Add a way for your users, for example your projects that the user has;
public function designs(){
$this->hasMany('Design');
}
For model models add the following methods:
public function user(){
$this->belongsTo('User');
}
public function products(){
$this->hasMany('Product');
}
For your product model
public function design(){
$this->belongsTo('Design');
}
They will establish relationships that allow you to load data into your models.
It can be done like this;
$variable = Product::with('designs')->find(1); //This will load the product with the related designs
If you want all projects and users owned by projects to 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.
Use the following to access properties:
$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.
Information display example;
@foreach ($variable->designs as $design)
{{ $design->user->username }}
@endforeach
Please note, I have not tested this code.
source to share