mercredi 16 novembre 2016

Get laravel data with relation between tables

I have the following data models:

class Cliente extends Model
{
     public function sector()
     {
           return $this->belongsTo(Sector::class,'sectoresId');
     }
}
class Sector extends Model
{
     public function sectorLanguage()
     {
           return $this->hasMany(SectorLanguage::class,'sectoresId');
     }

     public function cliente()
     {
          return $this->hasMany(ClienteLanguage::class,'sectoresId');
     }
}
class SectorLanguage extends Model
{
     public function sector()
     {
        return $this->belongsTo(Sector::class,'sectoresId');
     }

     public function idioma()
     {
        return $this->belongsTo(Idioma::class,'idiomasId');
     }
}

I want to recover all the active clients and the name of the sector to which it belongs, if I do something like this

$cliente = Cliente::where('active','1');

When I run $client I can not enter the attribute

foreach($cliente as $cli) {
  $cli->sector->sectorLanguage->nombre;
}

Why? It only works for me when I find it by id

$cliente = Cliente::find(1);
echo $cliente->sector->sectorLanguage->nombre;

How can I get what I need without resorting to doing SQL with Query Builder.

Thank you very much, greetings.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire