How to get one to many relations to a pivot - laravel

I have 2 models Scheme & Sponsor with a many-to-many relationship with pivot SchemeSponsor.
The pivot table has a one-to-many relationship with ContributionRate. I want to get all sponsors related to a scheme together with all contributionrates.
Scheme
id
name
Sponsor
id
name
SchemeSponsor
id
sponsor_id
scheme_id
pivot_data
ContributionRate
id
scheme_sponsor_id
rate
In the Sponsor model, I have this relationship
public function contribution_rates()
{
return $this->hasManyThrough(
ContributionRates::class,
SchemeSponsor::class,
'sponsor_id',
'scheme_sponsor_id',
'id',
'id'
);
}
This relationship returns all contributionrates even where the Scheme - Sponsor relationship does not exist. I want the rates that are related to the Pivot table SchemeSponsor. How can I achieve this via eager loading?

Seems like you are wanting to do a has-many-through-many-to-many which isn't supported by Laravel
You can, however, use eloquent-has-many-deep from jonas-staudenm (which makes your life much easier)
e.i. on Your Scheme Model
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function sponsors() {
return $this->belongsToMany(Sponsor::class);
}
public function contributionRate() {
return $this->hasManyDeep(
ContributionRate::class,
['scheme_sponsor', Sponsor::class], // Pivot tables/models starting from the Parent
[null, null, 'scheme_sponsor_id']
);
}

I have used EagerLoadPivotTrait by Arjon Jason Castro to eager load pivot relations.
Scheme Model
class Scheme extends Model
{
return $this->belongsToMany(Sponsor::class)
->using(SchemeSponsor::class)
->withPivot(
'pivot_data',
);
}
Sponsor Model
use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Sponsor extends Model
{
use EagerLoadPivotTrait;
return $this->belongsToMany(Scheme::class, 'scheme_sponsor')
->withPivot(
'pivot_data',
);
}
Then, to get the Scheme together with Sponsors and Sponsors' contribution rates;
($scheme
->with('sponsors.pivot.contribution_rates')
->where('id', $scheme->id)->get()->toArray())[0]
I have noted in as much as $scheme is a single model, eagerloading sponsors with contribution rates returns all schemes with the sponsors plus the contribution rates.

Related

Laravel eloquent for four tables

I'm new to Laravel. I am developing a project. and in this project I have 4 tables related to each other
-Users
-Orders
-OrderParcels
-Situations
When listing the parcels of an order, I want to get the information of that order only once, the user information of that order once again, and list the parcels as a table under it. so far everything ok. but I also want to display the status of the parcels listed in the table as names. I couldn't add the 4th table to the query. do you have a suggestion? I'm putting pictures that explain the structure below.
My current working code is
$orderParcels = Orders::whereId($id)
->with('parcels')
->with('users:id,name')
->first();
and my 'orders' model has method
public function parcels(){
return $this->hasMany(OrderParcels::class);
}
public function users(){
return $this->hasOne(User::class,'id','affixer_id');
}
Note[edit]: I already know how to connect like this
$orderParcels = DB::table('order_parcels as op')
->leftjoin('orders as o','op.orders_id','o.id')
->leftjoin('users as u','o.affixer_id','u.id')
->leftjoin('situations as s','op.status','s.id')
->select('op.*','o.*','u.name','s.situations_name')
->where('op.orders_id',$id)->get();
but this is not working for me, for each parcels record it returns me orders and user info. I want once orders info and once user info.
Laravel provides an elegant way to manage relations between models. In your situation, the first step is to create all relations described in your schema :
1. Model Order
class User extends Model {
public function parcels()
{
return $this->hasMany(OrderParcels::class);
}
public function users()
{
return $this->hasOne(User::class,'id','affixer_id');
}
}
2. Model Parcel
class Parcel extends Model {
public function situations()
{
return $this->hasOne(Situation::class, ...);
}
}
Then, you can retrieve all desired informations simply like this :
// Retrieve all users of an order
$users = $order->users; // You get a Collection of User instances
// Retrieve all parcels of an order
$parcels = $order->parcels; // You get a Collection of User instances
// Retrieve the situation for a parcel
$situations = $parcel->situations // You get Situation instance
How it works ?
When you add a relation on your model, you can retrieve the result of this relation by using the property with the same name of the method. Laravel will automatically provide you those properties ! (e.g: parcels() method in your Order Model will generate $order->parcels property.
To finish, in this situation where you have nested relations (as describe in your schema), you should use with() method of your model to eager load all the nested relation of order model like this :
$orders = Orders::with(['users', 'parcels', 'parcels.situations'])->find($id)
I encourage you to read those stubs of Laravel documentation :
Define model relations
Eager loading
Laravel Collection
Good luck !
Use join to make a perfect relations between tables.
$output = Orders::join('users', 'users.id', '=', 'orders.user_id')
->join('order_parcels', 'order_parcels.id', '=', 'orders.parcel_id')
->join('situations', 'situation.id', '=', 'order_parcels.situation_id')
->select([
'orders.id AS order_id',
'users.id AS user_id',
'order.parcels.id AS parcel_id',
'and so on'
])
->where('some row', '=', 'some row or variable')->get();

Laravel Reference a One-to-Many Table through a Many-to-Many Relationship

I am having the most difficult time with this, and I'm not sure if the issue is the relationship or what. I have a 'users' table that has a many to many relationship (via a pivot table) with a 'practices' table. Practices, however, have a one-to-many relationship with a 'doctors' table, in which a practice can have many doctors, but a doctor can only belong to one practice. I also then have a many-to-many relationship between the doctors and a 'patients' table, which I would need to run counts and count-by-date sort of queries off of.
Currently, it is set to where a user can see what doctors they have by running a foreach loop on practices, and then on $practices->doctors. But this is not optimal, as the doctors then can't be sorted alphabetically and such. Can someone help me figure out how I can reference the doctor directly without needing the additional foreach loop?
This is my current code. Thanks in advance!
dashboard.blade.php
#foreach ($practices as $practice)
#foreach ($practice->doctors as $doctor)
Doctor Name: {{$doctor->full_name}}
Patient Count: {{$doctor->patients()->count()}}
#endforeach
#endforeach
DashboardController.php
$practices = User::find(Auth::user()->id)->practices();
return view('dashboard')->withPractices($practices);
there is no predefined eloquent relationship for your scenario. but we can create a relationship using another relationship.
I believe you have already created the relationship to 'practices' in the 'User Model' and 'doctors' in 'Practice Model'.
// in User Model
public function practices()
{
return $this->belongsToMany(Practices::class);
}
// in Practice Model
public funcion doctors()
{
return $this->hasMany(Doctor::class);
}
You need a 'doctors' relationship in the 'User Model'.
// in User Model
public function doctors()
$this->load(['practices.doctors' => function($query) use (&$relation) {
$relation = $query;
}]);
return $relation;
}
now you can get 'doctors' for a 'user' like this.
$doctors = User::find(Auth::user()->id)->doctors;
You can create a direct relationship by "skipping" the practices table:
class User extends Model {
public function doctors() {
return $this->belongsToMany(
Doctor::class,
'practice_user',
null,
'practice_id',
null,
'practice_id'
);
}
}

Laravel pivot with multiple columns

Hi I have a problem with Laravel`s pivot table.
I have the following tables: students, courses and lessons.
The table lessons is connected with courses through a foreign key courses_id, and the tables students and courses are connected through a pivot courses_students.
So I can access the information through students like this:
//Students model
public function courses()
{
return $this->belongsToMany(Courses::class,'courses_students','student_id', 'course_id')
->with('lessons');
}
//Courses model
public function lessons()
{
return $this->hasMany(Lesson::class);
}
This works completely fine for this kind of relationship, but I want to add a third column in the pivot with name lesson_id for the lessons table.
I am doing this because, sometimes I need to get a specific set of lessons from each course for each user.
I succeeded in doing so, by using a model courseStudent for the pivot table.
Using the model for pivot my calls became like this.
Student->with('courseStudent.courses')
->with('courseStudent.lessons')
->get();
This partially does what I need it to do, but I want to maintain the relation ship between courses and students.
Is there a way to achieve that?
Example from docs(go through Many To Many):
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
Pivot table is meant to use belongsToMany relationship on both entities.
So your students and courses should have it defined if you want pivot table between that is using eloquent default capacity.
As a side note pay attention on naming convention because that way you will reduce issues on minimum: pivot table should be tableanamesingular_tablebnamesingular where order is set by alphabetical order of tables' names (i.e. post_user Yes, user_post No).
Id fields in pivot table should be tablenamesingular_id.
You can set names however you want but this way you will have less unepected behavior in future using eloquent. All of this you have in documentation page and I recommend you go through it thoroughly.
Other way is to use dynamic properties for getting certain values. Example from docs:
$user = App\User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}
If you would like to manually change values in pivot table, you should create separate model for it that would be connected with that entity/table (pay attention that pivot model extends Pivot as in example from docs rather than Model):
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PostUser extends Pivot
{
// other definitions related
}
You can use join for third relation:
public function courses(){
return $this->belongsToMany(Courses::class,'courses_students','student_id', 'course_id')
->withPivot('lesson_id')
->join('lessons','lesson_id','=','lessons.id')
->select('lessons.id','lessons.title', ...);
}
If you are going to use the same pivot table for courses and lessons, you can to do something like this:
//Students model
public function courses()
{
return $this->belongsToMany(Courses::class,'courses_students','student_id', 'course_id')
->whereNotNull('course_id');
}
public function lessons()
{
return $this->belongsToMany(Lessons::class,'courses_students','student_id', 'lesson_id')
->whereNotNull('lesson_id');
}
Then just use it:
$courses = $student->courses;
$lessons = $student->lessons;

Complicated Eloquent relationship using `Model::query`

I have a complicated relationship I'm trying to establish between two models.
The goal is to use $supplier->supply_orders to access the orders where the user supplies an item.
This throws: LogicException: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation.
With the code I've got I can use $supplier->supply_orders()->get(), however, when I try to use it as a relationship it throws. Since this is a relationship I should be able to wrap it in a relationship, but how would I go about doing that?
Supplier Model:
class Supplier extends Model {
public function supply_orders() {
return Order::query()
->select('order.*')
->join('item_order', 'order.id', '=', 'item_order.order_id')
->join('item', 'item_order.item_id', '=', 'item.id')
->where('item.supplier_id', '=', $this->id);
}
}
~~~ A whole lot of back info that I don't think you need but might ~~~
sql tables:
supplier
- id
items:
- id
- supplier_id
item_order:
- id
- order_id
- item_id
orders:
- id
The other Eloquent Models:
class Item extends Model {
public function orders() {
return $this->belongsToMany('Order');
}
}
class Order extends Model {}
Example of how this should work:
$supplier = factory(Supplier::class)->create();
$item = factory(Item::class)->create([
'supplier_id' => $supplier->id,
]);
$order = factory(Order::class)->create();
$order->items()->attach($item);
$orders = $supplier->supply_orders // Throws LogicException
This throws: LogicException: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
Sounds like a hasManyThrough with a many to many relationship. Laravel has no inbuilt support for this but you can always go ahead and write your own relationship like this: https://laravel.io/forum/03-04-2014-hasmanythrough-with-many-to-many
If you dont want relationships you can always do something like:
Order::whereHas('items.supplier', function($query) use($supplier) {
$query->where('id', $supplier->id);
});
For this to work, you need to have a relationship function items in your Order model and a relationship function supplier in your item model
I believe the reason it throws a relationship error is that you haven't created an Eloquent relation for
$supplier->supply_orders.
Instead, Laravel looks at your supply_orders() as a method in the class, and thus can't figure out which table to use as the pivot. To get the base relationship to work within Eloquent, you'd need to create a new pivot table for the relationship between suppliers and orders something like:
suppliers
-id
orders
-id
order_supplier
-id
-order_id
-supplier_id
From here, Laravel will accept a simple many to many relationship between the two (this would not cause a failure):
Supplier Class:
/**
* Get all orders associated with this supplier via order_supplier table
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function orders(){
return $this->belongsToMany("\App\Order");
}
Now that the relationship is solid both between the suppliers and orders, as well as the orders and items, you can eager load the relationship in all directions. Where it gets complicated for your particular need with the current DB setup is that you have a 3rd parameter from the items table that is not a direct pivot. Without having to re-structure the DB, I think the easiest would be to load your suppliers and the relationships like normal:
$suppliers = Supplier::with('orders', function($query) {
$query->with('items');
});
From here you've got all the relationships loaded and can draw down the ones with the right item->ids in a follow-up to the $suppliers collection. There are quite a few ways to skin the cat (even including all in one query) now that you have the Eloquent relationship... but I tend to keep it a little more simple by breaking it into a few readable bits.
Hope this helps.

Laravel - Relationship between a table with two other tables

I have 3 tables: users, pools, permissions. Users and Pools have a pivot table since they have a many-to-many relationship.
Permission entries are created by me only manually. Then, each pool can assign permissions to their own users as they see fit. Therefore, the pivot table for linking users to permissions needs to have both pool_id and user_id and permission_id
So how does this pivot table work? How do I make a three-way pivot table?
EDIT: My question is basically asked here, with no satisfactory answer!
For pivot table linking 3 models you need additional data send when attaching models like in this answer: Laravel - Pivot table for three models - how to insert related models?:
$model->relation()->attach($otherModel, ['thirdModelKeyName' => 'thirdModelKeyValue']);
You can create custom relation class, say ThreeBelongsToMany, that will extend belongsToMany and override attach() method.
Then override belongsToMany() method on your models, that are involved in such relation (or use a Trait there) to return mentioned custom relation class instead of generic belongsToMany when applicable.
The attach() method could look like this:
public function attach($id, array $attributes = array(), $touch = true, $otherId = null)
{
if ( ! is_null($otherId))
{
if ($otherId instanceof Model) $otherId = $otherId->getKey();
$attributes[$this->getThirdKey()] = $otherId;
}
return parent::attach($id, $attributes, $touch);
}
Also you can use some helpers to fetch those related models, like for example (key names should be obtained with methods for flexibility, they are hard coded to make it short):
/**
* Accessor for far related model (thru pivot)
*
* #return mixed
*/
public function getTrackAttribute()
{
if (is_null($this->pivot)) return null;
if (is_null($this->pivot->track_id)) return null;
return ($this->pivot->track) ?: $this->pivot->track = Track::find($this->pivot->track_id);
}

Resources