Instead of using Array, do following
Article::with('release')->find(123);
public function release()
{
return $this->hasOne('App\Release')->select('id');
}
I'm trying to just get the ID from a hasOne relation.
public function release()
{
return $this->hasOne('App\Release');
}
If I run
Article::with(['release'])->find(123);
I get the article and the related release. But instead of getting all of the data from the release table I only want to get the ID.
public function release()
{
return $this->hasOne('App\Release')->select(['id']);
}
The above doesn't work. The release relation is null. If I enable query logs and copy paste the query Laravel is making I can get the ID.
Is this a bug, that I can't only select the id? If I change it to this:
public function release()
{
return $this->hasOne('App\Release')->select(['id', 'article_id']);
}
then it works.
Your first example doesnt work because you dont include the foreign key to article in the select. It would work with select(['id', 'article_id']). It is because the eager loading mechanism needs the article_id to associate the release with its article.
Why only loading the id ? it mess up with your relationship, what if in some other case you want more info about the release ? If it is for presentation concerns (display it as json) you should use a presenter to format your data before displaying it. If it is for performance concerns, the performance gains are negligible and does not worth it.
Please or to participate in this conversation.