Pedro Filipe
Pedro Filipe

Reputation: 1

Laravel relationship always returning empty array

I have two models in a Laravel application Ft and Fi.

Ft contains the following code:

protected $table = 'ft';

protected $connection = 'XXX';

protected $keyType = 'string';

public function lines()
{
    return $this->hasMany('App\Fi', 'ftstamp', 'ftstamp');
}

Fi contains the following code:

protected $table = 'fi';

In my controller I have the following code

Ft::select($fields)->with(['lines'])

All results have "lines": []

Relationship exists in database.

Database is SQL Server

ft.ftstamp and fi.ftstamp field is type char.

Driver used for connection is sqlsrv.

Upvotes: 0

Views: 519

Answers (1)

miken32
miken32

Reputation: 42709

I'm sure this is a duplicate, but I can't find it. If you only select certain fields from the table, ensure that the primary key is one of them. The eager load is done as a separate query, not a join, so the key values have to be available.

For example, this code:

User::select(["id", "name"])->with("posts")->get();

Runs two database queries:

SELECT id, name FROM users;
SELECT * FROM posts WHERE user_id IN (?, ?, ?, ?...);

The second query is populated with the id values from the first. Without those values, the second query can't be run.

In a normal database, this would mean making sure that the array $fields contains "id" as an element, and I'd provide a code sample. Your database looks frightening however, so I won't try.

Upvotes: 1

Related Questions