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

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.

Related

Laravel - Many to Many on pivot table with Eloquent

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!

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');
}
}

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???

Laravel Eloquent Joins

I have below query in core php:
SELECT DISTINCT device_tocken FROM push_details JOIN users ON users.id=push_details.user_id
I have to integrate it in laravel 4
Application already have User extends Eloquent class
I created Push_details class as below
class Push_details extends Eloquent {
public $table = 'push_details';
public function User() {
return $this->hasMany('\User','id');
}
}
Table : users
Primary key : id
Table: push_details
Primary key: id
Foreign key: user_id belongsTo('users.id');
But i m not able to get expected result.
One more thing i didn't write anything in User's model yet.
Only way to join table is.. to join it, as Eloquent relations don't work using joins but separate queries with WHERE IN clauses. So this will do:
DB::table('push_details')
->select('device_tocken')
->distinct()
->join('users','users.id','=','push_details.user_id')
->get();
Above will return array of stdObject's so or if you need Eloquent Collection with Eloquent models as a result replace DB::table('push_details')->select... with PushDetails::select...
Now, correct your relations, as they are wrong:
// PushDetails model (as previously stated, I suggest renaming it to StudlyCase)
public function user() {
return $this->belongsTo('\User','user_id'); // user_id is may be omitted here
}
// User model
public function pushDetails() {
return $this->hasMany('\PushDetails','user_id'); // user_id is may be omitted here as well
}
In your User model, you need to link back to the PushDetails model, like so
class User extends Eloquent {
public function push_details() {
return $this->belongsTo('PushDetails');
}
}
Use CamelCase for Class names, because laravel has several functions, in which CamelCase are changed to snake_case
Change
public function User() {
return $this->hasMany('\User','id');
}
to
public function users() {
return $this->hasMany('User');
}
See the docs 'Eloquent ORM' for more...

laravel4 one to one relationship can not load the relationship

I have two tables like this:
users
id email
1 abc#ibm.com
2 abc#hp.com
3 abc#google.com
grp_members
grp_id user_id
1 2
2 2
13 1
13 3
2.My model
There, one group member must be a user, so its a one to one relationship just for GroupMember.
Users model about table users
class Users extends Eloquent {
protected $table = "users";
}
GroupMember model about table group_members
class GroupMember extends BaseModel{
protected $table = "grp_members";
public function user(){
return $this -> hasOne('Users', 'id');
}
}
3.In my service GroupApi.php, if I have a query like this
class GroupApi {
public function queryGroupMembers(){
$result = GroupMember::all();
var_dump(get_class(GroupMember::all())); //CODE ONE
foreach($result as $ret){
var_dump(get_class($ret)); //CODE TWO
var_dump(get_class($ret -> user)); //CODE THREE
}
}
}
As you see, when I invoke var_dump(get_class(GroupMember::all())) at CODE ONE,
I got this
.string(39) "Illuminate\Database\Eloquent\Collection"
Yes, that's what I want.
Now, at CODE TWO, it prints
string(11) "GroupMember"
Yes, also correct object, but when the code goes to CODE THREE, it give me a surprise,
the outputs like this:
string(8) "GroupApi"
Why its an instance of GroupApi, but not the instance of Users or GroupMember
And in that case , how can I invoke $ret -> user?
Any idea is welcome, thanks very much.
There are some things I'm not sure I understand in your implementation but something that could be causing you troubles is not using the conventions Laravel asks for, that being using User as the model name and users (model + s) as the table name.
Also, i would guess $g1 is not a GroupMember object as you suggest, could you getClass() it and comfirm?
Ok, I guess you have 3 tables:
users; grp_members; groups
and a many-to-many relationship between users and groups using the table grp_members as pivot table.
In this case, try this:
Class User:
class User extends Eloquent {
public function groups()
{
return $this->belongsToMany('Group', 'grp_members');
}
}
Class Group:
class Group extends Eloquent {
public function users()
{
return $this->belongsToMany('User','grp_members');
}
}
And also change the field name in the table 'grp_members' from grp_id to group_id, to follow eloquent conventions.

Categories