I have two tables: users
, orders
. I try to get all orders for current user.
Users Orders
_____ ______
id | name id | user_id
User model:
public function orders(){
return $this->hasMany("App\Order");
}
Order model:
public function user(){
return $this->hasOne("App\User", 'user_id', 'id');
}
Query in controller:
public function index()
{
$orders = Order::where('user_id', Auth::guard('api')->id())->get();
return response()->json(
$orders->user
);
}
I get NULL result, I do something wrong, because there are related rows in both tables.
In the category_product table, you can see product_id 1 have multiple entiries with category_id 2 and 3. That's how you can create many to many relationships in Laravel Eloquent. Obviously, you can use the inverse of this relationship to attach a category to multiple products.
A belongsTo() relationship matches a related table's 'id' to a 'localKey' field on 'this' model. Another way to think about it is the belongsTo() relationship should live on the model that has the field that links to the related tables id.
The pivot table in laravel is a structured value that is grouped and aggregated in the individual items where the extensive table is obtained or accessed in the form of a spreadsheet, database, or other discrete functions.
If you want to retrieve all the Orders belonging to the current user, try using the following function.
public function index()
{
$orders = Auth::user()->with('Orders')->get()->toArray();//To get the output in array
/* ^ ^
This will get the user | This will get all the Orders related to the user*/
return response()->json($orders);
}
As pointed out by @Martin Heralecký, you would also need to change the hasOne()
to belongsTo()
in Order Model. See following (copied from @Martin Heralecký answer)
public function user(){
return $this->belongsTo("App\User");// second and third arguments are unnecessary.
}
has_one
and belongs_to
generally are the same in the sense that they point to the other related model. belongs_to
make sure that this model has the foreign_key defined. has_one
makes sure that the other model has_foreign key defined.
Your $orders
array will look something like this:
User => [
id => 'user id',
name => 'user name'
orders => [
0 => [
//order data
]
1 => [
//order data
]
.
.
.
.
]
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With