We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Imagine you have two tables posts
and authors
. Posts table has a column author_id
which represents a belongsTo
relationship on the authors table.
To get the author id of a post, we would normally do
$post = Post::findOrFail(<post id>);
$post->author->id;
This would result in two queries being executed.
select * from posts where id = <post id> limit 1
select * from authors where id = <post author id> limit 1
Instead, you can directly get the author id by doing the following.
$post = Post::findOrFail(<post id>);
$post->author_id; // posts table has a column author_id which stores id of the author
When can I use the above approach? You can use the above approach when you are confident that a row always exists in authors table if it is referenced in posts table.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.