获取 laravel 个具有表间关系的数据

Get laravel data with relation between tables

我有以下数据模型:

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

如果我这样做,我想恢复所有活动客户端及其所属扇区的名称

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

当我运行$client我无法输入属性

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

为什么?只有当我通过 id

找到它时它才对我有用
$cliente = Cliente::find(1);
echo $cliente->sector->sectorLanguage->nombre;

如何在不借助查询生成器 SQL 的情况下获得所需内容。

非常感谢,问候。

根据你定义的关系,Sector有很多sectorLanguage,这意味着你收到了一个collection,所以你应该像这样处理一个对象:

$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

希望它有用!