mercredi 11 mars 2020

How to relate three models in laravel?

I'm trying to relate three models in laravel

This is my first model

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Tbl_Lista_Contactabilidad extends Model
{
protected $table = "tbl_lista_contactabilidad";
protected $fillable = [
'id', 'postventaatc_id', 'rif', 'razon_social', 'estatus', 'fecha_contacto', 'persona_contacto', 'correo_contacto', 'celular_contacto', 'numero_contacto', 'comentarios', 'contactado', 'auditado'
];
protected $guarded = ['id'];

public function postventaatc(){

return $this->belongsTo('App\Models\Tbl_Equipo_Postventaatc','postventaatc_id');
}
}

This is the second model... I'm trying to use this model like a bridge between the other two models

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Tbl_Equipo_Postventaatc extends Model
{
protected $table = "tbl_equipo_postventaatcs";
protected $fillable = [
'asesor_id', 'carteras_id', 'supervisor_id', 'skillcontacs_id', 'workgroupcontacs_id', 'estatus'
];
protected $guarded = ['id'];
public function users(){
return $this->belongsTo('App\User','asesor_id');
}
public function contactabilidad(){

return $this->hasMany('App\Models\Tbl_Lista_Contactabilidad','postventaatc_id');
} 
}

And this is my third model... I would like to join the first model with this

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = "users";
protected $fillable = [ 
    'idop', 'name', 'apellido', 'cedula',
    'fecha_nacimiento', 'fecha_ingreso', 'extension',
    'movil', 'tel_hab', 'email', 'password', 'generos_id',
    'empresas_id', 'gerencias_id', 'cargos_id',
    'direccion_personales_id', 'nivelacademicos_id',
    'personal_guardia', 'estatus',
];
protected $guarded = ['id'];

public function postventaatc(){
return $this->hasMany('App\Models\Tbl_Equipo_Postventaatc','asesor_id');
}
}

I'm trying to relate theese three models for this function

public function map($contactabilidad): array
{
    return [

        $contactabilidad->postventaatc_id,
        $contactabilidad->postventaatc->name,
        $contactabilidad->rif,
        $contactabilidad->razon_social,
        $contactabilidad->fecha_contacto,
        $contactabilidad->persona_contacto,
        $contactabilidad->correo_contacto,
        $contactabilidad->numero_contacto,
        $contactabilidad->celular_contacto,
        $contactabilidad->comentarios,
        $contactabilidad->contactado,
        $contactabilidad->respuesta->respuesta
    ];
}

But I obtained this error "ErrorException Trying to get property 'name' of non-object"

What should I do?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire