Answer the question
In order to leave comments, you need to log in
What will work faster: connection or join?
Good afternoon.
From time to time I use either connections or joins. And now I want to choose one thing for further work. But I do not know what is more efficient and faster. The goal, as usual, is to optimize the database so that the project opens faster, even if only for a fraction of a second.
So. Let's analyze the most common example with a book and an author. There is a table with books, there is a table with authors. They are connected like this: in the table with books, each book has an author_id. You can make a connection:
public function author() {
return $this->belongsTo(User::class);
}
SELECT books.*, authors.name as author_name FROM books
LEFT JOIN authors
ON books.author_id = authors.id
$books->author;
$books->author_name;
$books = "SELECT * FROM books LIMIT 1";
$author = "SELECT name FROM authors WHERE id = " . $books->author_id;
foreach($books as $book) {
echo $book->name . '<br>';
echo $book->author;
}
Answer the question
In order to leave comments, you need to log in
use eager loading to load the model and all relationships at once if you are sure that they are all needed. (with)
If there is not so much data, I think it's better to use left join and completely load the context, if there are already a lot of indexes there, but it's always better to stick to the tenancy between the database performance and the web performance.
The connections are clearer. No matter which is faster, speed is overrated. The speed of the programmer is much more important in the vast majority of cases. Auto-suggestions in the IDE save time on typos, the code looks much clearer in a year, without "but where did this field come from?"
LEFT JOIN is usually used where ORM is not used, but this is not necessary everywhere and where resources are saved or when rewriting old projects while maintaining the database structure. I think that with your projects (no offense, mine too;) ) ORM capabilities are more than enough for everyday work. Just feel all the possibilities of ORM and don't think about other things for now)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question