I need help with Laravel 5.4 relationships.
I have 4 tables:
users (fileds: id, name, etc.)
profiles (fields: id, user_id, first_name, last_name)
orders (fields: id, user_id, etc.) order_items (fields: id, order_id, product_id, etc.)
A user can have one profile
A profile can have one user
A user can have many orders
An order an have one user
An order can have many items
In the models I have:
User:
public function profile()
{
return $this->hasOne('App\Profile');
}
public function orders()
{
return $this->hasMany('App\Order');
}
Profile:
public function user()
{
return $this->belongsTo('App\User');
}
Order:
public function user()
{
return $this->hasOne('App\User');
}
public function order_items()
{
return $this->hasMany('App\OrderItem');
}
orderItem:
public function order()
{
return $this->belongsTo('App\Order');
}
public function product()
{
return $this->hasOne('App\Product');
}
I have two questions:
1. When I show an order, I want to show the first_name and last_name columns from the profiles table.
In my controller I did this: $user = User::find($order->user_id);
In my view:
Is there a way to get the name directly in the view and not fetch the user first in the controller?
2.
In my Order model:
When I view the order I want to display all the order items and the product name (product->name) for each item.
I'm very confused and don't know how to do this.
In my controller I tried: 1.
$items = Order::find($order->id)->order_items->with('product');
Got an error: Trying to get property of non-object
2. $items = Order::find($order->id)->order_items;
foreach($items as $item) {
echo $item->product->name;
}
Got an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.order_item_id' in 'where clause' (SQL: select * from products
where products
.order_item_id
= 1 and products
.order_item_id
is not null limit 1)
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire