Beusebiu
Beusebiu

Reputation: 1523

Get values from relationship Laravel

I have a query where I get values from 3 tables, for first 2 I use leftJoin, and is Ok, but for third one I try to get an array of objects, and I am not sure how. In relationship table a have multiple rows for each ID from People table. HasMany type.

$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);

Person

public function relationship()
{
    return $this->hasMany(Relationship::class);
}

public function register()
{
    return $this->belongsTo(Register::class);
}

Relationship

public function person()
{
    return $this->belongsTo(Person::class, 'person_id');
}

Register

public function people(){
    return $this->hasOne(Person::class);
}

UPDATE -> this works,but is kind of ugly, I think that should be a better way in Laravel

$q = Person::leftJoin('registers', 'people.register_id', '=', 'registers.id')
            ->find($id);
$q2 = Person::find($id)->relationship;
return response()->json([
    'values' => $q,
    'relationship' => $q2,
]);

Upvotes: 0

Views: 72

Answers (1)

TsaiKoga
TsaiKoga

Reputation: 13404

You can just use with like this:

Person::with(['register', 'relationship'])->find($id);

Upvotes: 3

Related Questions