monchyrcg monchyrcg - 19 days ago 7
PHP Question

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.

Answer

According to your defined relations, the Sector has many sectorLanguage, it means you're receiving a collection, so you should work on an object like this:

$cliente->where('active', 1)
            ->first()
            ->sector
            ->sectorLanguage
            ->first()
            ->nombre;

Cliente::where('active', 1) and sectorLanguage gives you the collection, so you should first get the first item from $cliente & sectorLanguage and then apply the desired relationship

Hope it should work!

Comments