Trying to achieve a hasManyThrough type relationship - laravel

I'm trying to achieve something that is similar to Laravel's hasManyThrough, but I'm not sure my DB is set up appropriately or I'm just missing something.
I am trying to display a page for admins to show all of the sites we support. I would like to have a simple column that shows a distinct count of how many customers are attached to each site. To do this, I was going to go through the orders table and retrieve a distinct list of users, then simply use the ->count() method inside my view.
Here is my DB setup (simplified):
sites table (primary key: 'id'):
id | ...
users table (primary key: 'id'):
id | first_name | last_name | ...
orders table (primary key: 'order'):
id | order | user_id | site_id | ....
Site model:
public function customers()
{
return $this->hasManyThrough('App\User', 'App\Order', 'site_id', ' id')->distinct();
}
I realize right away that the key difference between my DB setup and the documentation is I do not have an order_id in my users table, but it doesn't make sense that I do since a user can have many orders.
It is worth noting: I also have a table user_orders. I'm not sure if I should be using that instead. user_orders has the following set up:
id | user_id | order
You can see that it is simply an intermediate table to hold connections between users and orders (remember order is the PK in orders, not id).
So, can anyone help me understand what I am doing wrong?

You could get away with a Join. I give you this sample code to guide you
public function customers()
{
return $this->hasMany('App\Order')
->leftjoin('users', 'users.id', 'orders.user_id')
->groupBy('users.id'); //Is this needed?
//Above code will return you a collection of Order though, but with the user data.
//Let's try using the User model
return App\User::whereHas('orders', function($query) use ($this->id) {
$query->where('site_id', $this->id);
})->get();
}

Related

Retrieve values from related table foreign key using Eloquent

Sorry if the question isn't clear.. I'm not super fluent in databases.
I have three tables:
companies equipment parts
----------- ----------- -----------
id id id
name company_id equipment_id
Using Eloquent, how do I get a Collection of all the parts that belong to the company with id=1
I know you setup relationships in the model. So now I can get all a company's equipment ($myCompany->equipment), and all equipment's parts ($myEquipment->parts), but I'm not sure how to easily get values in the reverse direction two tables away.
Thanks!
Laravel has such a beautiful documentation and API for this very thing. Take a look at the hasManyThrough relationship.
So in your Company model add this:
/**
* Get all of the parts for the company.
*/
public function parts()
{
return $this->hasManyThrough('App\Part', 'App\Equipment');
}

Laravel pivot sync() attaches wrong values

I've been dealing with this issue on almost every sync() to the pivot tables where, in Laravel 5.6, when I perform the following it adds one row that is non existent in the request:
$firm_data = request()->all(); // get the request data
$firm = Firm::where('id', request('firm_id')); // get the Firm model
$firm->update($firm_data); // update the model
// add the firm address with a belongsToMany() relationship set on Models\Firm and on Models\Address
$address = $firm->with('addresses')->first();
$addresses = request('addresses'); // get the request data for address
$address->update($addresses); // all ok till here
// deal with the pivot table
// here's the issue...
$address->cities()->sync([request('firm_id'), $addresses['city_id']]);
The firm data and the address data state is saved correctly in the DB, although, the pivot table is filled with two columns instead of one.
I have, in the whole request, one only city_id = 3034856 but to the pivot table it is added the first row firm_id = 1, city_id = 1, "which comes from nowhere":
The pivot table - firm_city
+---------+---------+
| firm_id | city_id |
+---------+---------+
| 1 | 1 |
| 1 | 3034856 |
+---------+---------+
Any thoughts on why this might be happening?
Just to make sure it's right, here the methods for each model Firm and Address:
// On the Firm model
public function cities()
{
return $this->belongsToMany(City::class, 'firm_city');
}
// on the City model
public function firms()
{
$this->belongsToMany(Firm::class, 'firm_city');
}
Thanks in advance for any insight on why this might be happening,
Remove the firm_id:
$address->cities()->sync([$addresses['city_id']]);
Eloquent gets the firm_id from $address, you don't have to specify it.
If you specify
it, Eloquent assumes that you want to sync a City with id=1.

Laravel belongsToMany pivot with multiple columns

I currently have two tables in the DB and a pivot table to join them when I need to do a belongsToMany lookup. The basic example is one DB table is 'teams' and the other is 'members'. I can utilize the belongsToMany method on both the team and members model to pull their relationship with each other. A team can have many members, and a member can belong to many teams.
public function teams()
{
return $this->belongsToMany(Team::class);
}
public function members()
{
return $this->belongsToMany(Member::class);
}
Pivot: team_member
team_id | member_id
---------------------
1 | 1
2 | 1
3 | 2
1 | 2
How can I expand on that pivot table to include a type of member for each team? For example, member1 is a leader on team1. member1 is an assistant on team2. member1 is a generic member on team3... and so on. Can I just add a column to that same pivot table? Would it be the membertype_id? How can I relate that to another model/table?
This is pretty common, and Laravel handles it already. Add extra columns to the pivot table and expand your relationships to use withPivot():
public function teams(){
return $this->belongsToMany(Team::class)->withPivot(["teamRole", ...]);
}
Then accessing is as simple as:
$user = \App\User::with(["teams"])->first();
$team = $user->teams->first();
$teamRole = $team->pivot->teamRole;
See the Documentation for more information:
https://laravel.com/docs/5.6/eloquent-relationships
To answer the second part, which is essentially a "Triple Pivot", that requires extra functionality. See
Laravel - Pivot table for three models - how to insert related models?
for more information, and an associated Package (by the answerer on that question, not maintained, but good for an example)
https://github.com/jarektkaczyk/Eloquent-triple-pivot

Joining an additional table with belongsToMany()?

This question is best illustrated by an example:
users
id
name
roles
id
name
role_user
user_id
role_id
rank_id
group_id
...
ranks
id
name
groups
id
name
I can easily eager load a users table by specifying the following relationship in my User.php model:
public function roles() {
return $this->belongsToMany('Role');
}
Which will output the table below when calling User::with('roles'):
User | Role
-------------
Jon | Admin
Jan | Mod
However I have no idea how to extend this to include:
User | Role | Rank | Group
-----------------------------
Jon | Admin | Boss | Blue
Jan | Mod | Minion | Red
What I've tried doing User::with('roles', 'ranks', 'groups') but that is certainly wrong since I'm telling Laravel there are rank_user and group_user intermediate tables too but there aren't. What is the correct way?
PS: I know it's better to separate the ranks and groups into their own relationship/pivot tables, this is simply an example.
EDIT: Closest example I can find for this: https://github.com/laravel/framework/issues/2619#issuecomment-38015154
You can just treat your model's relations methods as ordinary queries and build upon them:
public function roles() {
return $this->belongsToMany('Role')
->join('role_user', 'role_user.role_id', '=', 'roles.id')
->join('ranks', 'ranks.id', '=', 'role_user.rank_id')
->join('groups', 'groups.id', '=', 'role_user.group_id');
}
Relations queries like the above are not so intuitive to understand when they get too complex, so it may be better to rethink database design, but in theory it's possible to manipulate them.

Laravel Many to Many - 3 models

Some help with many to many relationships in Laravel:
Using the example for roles and users - basically:
a table for all the roles
a table for the users
and table with user_id and role_id.
I want to add to the third table, eg Year. basically the pivot table will have user_id, role_id and year_id.
I want to be able to make a query to pull for example all users assigned a specific role in a specific year. Eg All users with role_id = 2, and year_id = 1.
Any help will be appreciated
Before answering, I would like to suggest you not to put year on database like this.
All your tables should have created_at and updated_at which should be enough for that.
To filter users like you want. You could do this:
// This queries all users that were assigned to 'admin' role within 2013.
User::join('role_users', 'role_users.user_id', '=', 'users.id')
->join('roles', 'roles.id', '=', 'role_users.role_id')
->where('roles.name', '=', 'admin')
->where(DB::raw('YEAR(role_users.created_at)', '=', '2013')
->get();
This example may not be the precise query you are looking for, but should be enough for you to come up with it.
The best way to achieve a three way relation with Eloquent is to create a model for the table representing this relation. Pivot tables is meant to be used for two way relations.
You could have then a table called roles_users_year which could have data related to this 3 way relation like a timestamp or whatever...
A very late answer to a very old question, but Laravel has supported additional intermediate (pivot) table columns of at least Laravel 5.1 judging from the documentation, which hasn't changed at least through Laravel 6.x.
You can describe these extra columns when defining your many-to-many relationship:
return $this->belongsToMany(Role::class)->withPivot('column1', 'column2');
or in your case, the below would also do the job:
return $this->belongsToMany(Role::class)->withTimestamps();
which you can then access via the pivot attribute on your model:
$user = User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}
Note that the pivot attribute is on the distant relationship model (a single Role) and not on the relationship itself.
To get all the Roles assigned to Users in any given year, you might create a special relationship:
// User.php
public function rolesInYear($year) {
return $this->belongsToMany(Role::class)
->wherePivot('created_at', '>=', Carbon::create($year))
->wherePivot('created_at', '<', Carbon::create($year + 1));
}

Resources