question about laravel relationships and performance

Viewed 502

i hope you are having a good time. i am learning laravel and the inscuctor talked about when you load relationships in laravel, like so

    public function timeline()
    {
        $ids = $this->follows()->pluck('id');
        $ids->push($this->id);
        return Tweet::whereIn('user_id', $ids)->latest()->get();
    }

and i have a follows relationship in my model, and he talked about this line

$ids = $this->follows()->pluck('id');

being better for performance than this line

$ids = $this->follows->pluck('id');

my question is, how does laravel pluck the ids in the first case, and how it queries the database i hope im making sense, thanks for your time, and answer.

1 Answers

the following one executes a select query on database

$this->follows()->pluck('id');

the follows() returns a query builder (which is a not yet executed sql statement) and then on the result select the id column and returns a collection of ids

you can see the query by dumping the query builder by $this->follows()->dd()

Whereas in the second option

$this->follows->pluck('id')

up until $this->follows laravel executes a query and returns all the records as a collection instance, You will be able to see all the attributes on each of the records. And then ->pluck('id') is getting executed on the laravel collection class, which will do an operation I assume similar to the array_column function does and returns only the id column.

as you can easily see in the second operation the whole data set was retrieved first from the DB and then selected the required attribute/column (2 distinct and heavy operations). Where as in the first option we directly told eloquent to select only the required column, which is only one lighter operation compared to the second option.

Related