The Eloquent JoinWith package by Mohammed Safadi lets you join existing HasOne and BelongsTo model relationships with a new joinWith() method. According to the package's readme, JoinWith will execute a single query instead of two separate queries, which can translate to faster and more efficient queries.
To use this package, you can either use the package's JoinWith trait or extend the package's provided JoinWithModel class:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Safadi\EloquentJoinWith\Database\Concerns\JoinWith;
class User extends Model
{
use JoinWith;
// ...
}
You can then call the joinWith() method, which resembles the with() method:
$user = User::joinWith('profile')
->select('users.id', 'users.name')
->first();
// Nested relationships
$user = User::joinWith('profile.country')->first();
// More complex example
$orders = Orders::joinWith(['user' => function ($query) {
$query->where('users.status', '=', 'verified');
}])->get();
This package works specifically with HasOne and BelongsTo model relationships—at the time of writing, other relationships are not supported. You can learn more about this package, get full installation instructions, and view the source code on GitHub at msafadi/laravel-eloquent-join-with.
The post Eloquent JoinWith Package for Laravel appeared first on Laravel News.
Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.
0 comments:
Post a Comment
Thanks