variable assigning to a similar variable

Viewed 41

New to stack overflow and new to the language. I have some confusion on how to read this code, trying to learn the logic of it. If somebody can explain it will highly appreciate it.

$relationships = $member->relationships()
    ->whereIn('type_id', $this->getRelationshipTypesFor(['daughter', 'son']))
    ->with('member2.gender')
    ->get();

I'm confused if $member is assigning the relationship() which the variable $relationship? or is it from a constant Laravel function. I'm a bit lost on how to read this. Cheers for the help.

2 Answers

It will be better to explain it with following code.

Assuming you have an model Person, which can have several Dog models. What you are doing, is calling to relationship between Person and Dog, and filtering it by the type of the Dog.

The function $this->getRelationshipTypesFor is just local func of class you are writting code in.

Eager loading ->with('member2.gender') means that Person model has relationship called member2, which has gender relationship. Honestly it's strange that the gender is relatioship there, but we don't know what is under the cover ¯_(ツ)_/¯. In example bellow I will name it as simple "dad" relationship.

// Person.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use App\Models\Dog;
use App\Models\Dad;

class Person extends Model {
    public function dogs() {
        return $this->hasMany(Dog::class);
    }

    public function dad() {
        return $this->hasOne(Dad::class)->where('id', $this->dad_id);
    }
}

Then the query for this model is:

$person = Person::find($id);

$people = $person->dogs()
            ->whereIn('breed', $this->getBreeds()); // for example response of $this->getBreeds can be ['bulldog', 'poodle']
            ->with('dad')
            ->get();

This is a so-called fluent interface. A fluent interface is an object with this special property: most methods of the object have the same return value - the object itself. So if you call any of these methods, you know that the return value is the same object again - the same instance of the same class.

In your example, the $member object has these methods:

  • relationships()

  • whereIn()

  • with()

  • get()

The $member calls its method relationships(), which returns Illuminate\Database\Query\Builder instance. Now it calls whereIn() on it, which returns inself, and then it calls the get() method, which returns Collection object.

Related