Reputation: 839
I'm new to laravel and I'm not really understanding how relationships work using it. I think I'm just having an "off" day as I'm struggling to do something relatively simple.
I have 2 tables. items and inventory
Each entry within the inventory table has a column labeled itemid and userid.
So for example, this could be the table inventory with its entries -
id | userid | itemid | ...
+-----------------------------------
| 1 | 1 | 1 | ...
| 2 | 1 | 4 | ...
| 3 | 1 | 6 | ...
| 4 | 2 | 1 | ...
(there are more columns but these are just the columns that link everything together)
Basically, what I'm trying to do is get all of the items that a user has. My normal method would just be using a JOIN query but I'm not really sure how it works in Laravel.
I have 2 very simple models just to retrieve the data from each table
Inventory.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Inventory extends Model
{
protected $table = 'inventory';
}
Item.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
protected $table = 'items';
}
How can I get the item data for each entry within the inventory table? I've tried defining relationships and such using the eloquent documentation but I must be doing something wrong.
Upvotes: 1
Views: 77
Reputation: 54831
In your case you have a many-to-many
relationship between User
and Item
, so there's no need to use Inventory
as a model, cause inventory
table is just a pivot table.
Your models can look like:
class User extends Model
{
public function inventory_items()
{
return $this->belongsToMany(
'Item', // joined model
'inventory', // pivot table name
'userid', // column name in pivot table
'itemid' // column name in pivot table
);
}
}
Items of user you can get with
$user = User::find($user_id);
$items = $user->inventory_items()->get();
Same technique can be applied to Item
model.
Update: for retrieving additional pivot table colums - update your inventory_items()
as:
public function inventory_items()
{
return $this->belongsToMany(
'Item', // joined model
'inventory', // pivot table name
'userid', // column name in pivot table
'itemid' // column name in pivot table
)->withPivot('column_1', 'column_2')
}
Upvotes: 2