从关系中获取值 Laravel
Get values from relationship Laravel
我有一个查询,我从 3 tables 中获取值,对于前 2 个,我使用 leftJoin,并且没问题,但是对于第三个,我尝试获取一个对象数组,但我没有确定如何。
在关系 table 中,人 table 的每个 ID 都有多行。有很多类型。
$q = Person::leftJoin('registers', 'people.register_id', '=', 'registers.id')
->leftJoin('relationships', 'people.id', '=', 'relationships.person_id') //if I comment this it works for first 2 tables
->find($id);
return response()->json($q);
人
public function relationship()
{
return $this->hasMany(Relationship::class);
}
public function register()
{
return $this->belongsTo(Register::class);
}
关系
public function person()
{
return $this->belongsTo(Person::class, 'person_id');
}
注册
public function people(){
return $this->hasOne(Person::class);
}
UPDATE -> 这个可行,但是有点难看,我认为在 Laravel
中应该是更好的方法
$q = Person::leftJoin('registers', 'people.register_id', '=', 'registers.id')
->find($id);
$q2 = Person::find($id)->relationship;
return response()->json([
'values' => $q,
'relationship' => $q2,
]);
您可以像这样使用 with
:
Person::with(['register', 'relationship'])->find($id);
我有一个查询,我从 3 tables 中获取值,对于前 2 个,我使用 leftJoin,并且没问题,但是对于第三个,我尝试获取一个对象数组,但我没有确定如何。 在关系 table 中,人 table 的每个 ID 都有多行。有很多类型。
$q = Person::leftJoin('registers', 'people.register_id', '=', 'registers.id')
->leftJoin('relationships', 'people.id', '=', 'relationships.person_id') //if I comment this it works for first 2 tables
->find($id);
return response()->json($q);
人
public function relationship()
{
return $this->hasMany(Relationship::class);
}
public function register()
{
return $this->belongsTo(Register::class);
}
关系
public function person()
{
return $this->belongsTo(Person::class, 'person_id');
}
注册
public function people(){
return $this->hasOne(Person::class);
}
UPDATE -> 这个可行,但是有点难看,我认为在 Laravel
中应该是更好的方法$q = Person::leftJoin('registers', 'people.register_id', '=', 'registers.id')
->find($id);
$q2 = Person::find($id)->relationship;
return response()->json([
'values' => $q,
'relationship' => $q2,
]);
您可以像这样使用 with
:
Person::with(['register', 'relationship'])->find($id);