Laravel - Many to Many on pivot table with Eloquent - php

I have three table which I wanna associate. Shipment_methods, Ship_companies and Payment_methods.
Relations:
Shipment_methods <- pivot1 -> Ship_companies
pivot1 <- pivot2 -> Payment_methods
Well, what I wanna do is e.g. ShipmentMethod_A is attached to ShipCompany_B and for this record (from pivot1) I wanna attach record from Payment_method table through pivot2 table.
ShipmentMethod Model:
public function ship_companies()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'shipment_method_id', 'ship_company_id')->withPivot('price_kc', 'price_ha');
}
ShipCompany Model:
public function shipment_methods()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'ship_company_id', 'shipment_method_id');
}
What I need to do is I wanna retrieve all Payments for ShipCompany of specific ShipmentMethod like
ShipmentMethods->ship_companies->pivot->payments_methods
Thanx.

I think best way is for you to have a Model that extend Pivoted class for you pivot1. the pivot1 should have id column to use in pivot2. so the code should be like this,
ShipmentMethod Model:
public function ship_companies()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'shipment_method_id', 'ship_company_id')->using('App\pivot1')->withPivot('id','price_kc', 'price_ha');
}
note that I have put id in withPrivot and chain using() method
your pivot1 model should be like this,
pivot1 Model:
use Illuminate\Database\Eloquent\Relations\Pivot;
class pivot1 extends Pivot
{
public function Payment_methods()
{
return $this->belongsToMany(Payment_methods::class, 'pivot2_table_name', 'pivot1_id', 'payment_method_id');
}
}
and at the end you can do like this to save to pivot2
ShipmentMethods->ship_companies->pivot->payments_methods()->sync([payment_method_ids])
as all pivot relationship return a collection of array note that you need to loop ShipmentMethods->ship_companies relationship to get to pivot relationship.
Hope this helps!

Related

How to join two tables with a pivot table using Laravel?

I have these three tables:
tbl_lista_contactabilidad tbl_equipo_postventaatc users
------------------------- ----------------------- -----
id id id
usuarios_id asesor_id name
tbl_lista_contactabilidad.usuarios_id should be related with tbl_equipo_postventaatc.asesor_id. asesor_id should be the "pivot" between tbl_lista_contactabilidad.usuarios_id and users.id to make the relation.
I want to make this relation so I tried to do this relation in this way (I will put only the relation of the model)
Tbl_Lista_Contactabilidad (Model 1)
public function postventaatc(){
return $this->belongsTo('App\Models\Tbl_EquipoPostventaatc','usuarios_id');
}
Tbl_Equipo_Postventaatc (Model 2) -> This should be the pivot model
public function contactabilidad(){
return $this->hasMany('App\Models\Tbl_Lista_Contactabilidad','usuarios_id');
}
public function user(){
return $this->belongsTo('App\Models\User','asesor_id');
}
User (Model 3)
public function postventaatc(){
return $this->hasMany('App\Models\Tbl_Lista_Postventaatc','asesor_id');
}
EXAMPLE:
As you see in the image... if I relate usuarios_id with users directly I will get another name and I don't want that... I want the relation just like in the image
A pivot table is a structure used to join two separate models together with a single relationship. This is called a many-to-many relationship in Eloquent.
From what you've described, this is not the case here. Rather, it looks like a has-many-through relationship.
If I'm understanding correctly, your relationships should look like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Tbl_Lista_Contactabilidad extends Model {
protected $table = 'tbl_lista_contactabilidad';
public function postventaatc() {
return $this->belongsTo(Tbl_EquipoPostventaatc::class, 'usuarios_id');
}
}
class Tbl_EquipoPostventaatc extends Model {
protected $table = 'tbl_equipo_postventaatc';
public function contactabilidad() {
return $this->hasMany(Tbl_Lista_Contactabilidad::class, 'usuarios_id');
}
}
class User extends Model {
public function postventaatc() {
return $this->belongsTo(Tbl_EquipoPostventaatc::class, 'asesor_id');
}
public function contactabilidad() {
return $this->hasManyThrough(Tbl_Lista_Contactabilidad::class, Tbl_EquipoPostventaatc::class, 'asesor_id', 'usuarios_id');
}
}
Obviously this is easier for a native English speaker, but I cannot stress how much easier this would be if you were following the Laravel rules around naming your models, tables, and columns. Why does usuarios_id column relate to a table called tbl_equipo_postventaatc? Why use asesor_id instead of user_id? 🤷🏽‍♂️ Those names have nothing to do with each other, and make it hard to figure out what is going on.

LARAVEL ELOQUENT - I want to add column from user table to a relation table

I am not much familiar with eloquent orm in laravel
I have 3 tables they are
-- leads
|
Lead_appointments
and users table
since lead_appointments belongs to leads references id on leads by lead_id
the leads_appointments has a column called created_by with user's id in it
I am trying to query user's name and email along with the result as another column when query using eloquent
Lead Model
class Leads extends Model
{
public function appointments()
{
return $this->hasMany('App\Models\LeadsAppointments', 'lead_id');
}
}
My eloquent query in controller
return $this->lead->with('appointments')->find($id);
the result is like this
In under appointments i also want user email and name along with created by in it
But I couldn't figure it out
Add a relation to LeadAppointment model like this:
class LeadAppointment extends Model
{
public function users()
{
return $this->belongsTo('App\Models\User', 'created_by');
}
}
and change leads model like this:
class Leads extends Model
{
public function appointments()
{
return $this->hasMany('App\Models\LeadsAppointments', 'lead_id')->with('users');
}
}

How to load a nested relationship in Laravel

I have a model called CallbackRequest the model has a relationship with Loan model and that is the only relationship for CallbackRequest model.
CallbackModel:
public function loan() {
return $this->belongsTo(Loan::class);
}
Now Loan model itself has a relationship with a third model called Applicant.
Loan Model:
public function applicant() {
return $this->belongsTo(Applicant::class);
}
My point:
When I load CallbackRequest I eagerload loan model with it, all fine! But now I am wondering if there is a way to eagerload applicant model when I do:
Right now I access it like:
$modelResults = PublicCallback::with('loan')->get();
I get all callbacks with loan eagerloaded, but my point is I want when I eagerload loans in this case I want applicant to be loaded also !
Is there any way how to do this, is it possible ?
You can do this with:
$modelResults = PublicCallback::with(['loan', 'loan.applicant'])->get();
Ref: https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
Just for posterity, there's also another way of loading nested relationships that can be done against a returned model, provided you have set up the relationships correctly:
Posts model:
public function comments() {
return $this->hasMany('App\Comment', 'quote_id', 'id');
}
Comments model:
public function user() {
return $this->belongsTo('App\User');
}
Then you can actually infer the user via relationship to a comment by drawing the post but loading an array of relations, eg:
$post = \App\Post::find($post_id);
return $post->load(['comments','comments.user']);

Laravel get model with relation's pivot condition

I need to get all appeals, that have appeal_stage.expiration_date less than NOW().
Now I have following solution:
public function scopeExpired($query) {
$query->join('appeal_stage', 'appeals.id', 'appeal_stage.appeal_id')
->where('appeal_stage.expiration_date', '<=', new Expression('NOW()'));
}
but resulted model dump shows that joined table is recognized as pivot table:
So, I want to ask - Is there some more convenient way to perform this request?
My suggestions is use Illuminate\Database\Eloquent\Relations\Pivot somehow, bu I do not quiet understand, how Pivot can be used here.
UPD 1
Models has next relations:
public function stages()
{
return $this->belongsToMany(Stage::class)->withPivot('prolongated_count', 'expiration_date')->withTimestamps();
}
public function appeals() {
return $this->belongsToMany(Appeal::class);
}
You should be able to do something like this:
$appeal->stages()->wherePivot('expiration_date', '<', $now)->get()
You should create relationship in appeal model
public function stages()
{
return $this->belongsToMany(Stage::class,'appeal_stage','appeal_id','stage_id')->wherePivot('expiration_date','<',Carbon::now())->withTimestamps();
}
In belongs To Many relationship second argument is your Pivot table name

Make a simple join to a reference table with Laravel 5.1 Eloquent

I have a simple join to make, but I can't do it.
I have a tournament that has a categoryId field in the table.
The table TournamentLevel is a 10 entry table.
So I would like to be able to retrieve level->name with Eloquent.
I tried to do the following:
In Tournament, I tried to define a hasOne relationship:
class Tournament extends Model
{
....
public function level()
{
return $this->hasOne('App\TournamentLevel');
}
But then, Eloquant is looking for tourmanent_id inside of TournamentLevel Table
So I tried the opposite,
In Model TournamentLevel:
class TournamentLevel extends Model
{
...
public function tournament()
{
return $this->belongsTo('App\Tournament');
}
}
And tried to reach :
tournament->level->name
but without success
It seems pretty elementary, but I can't do it... Any idea???

Categories