Laravel how to use model scope method inside join query - laravel

i want to use scope method inside join subquery so is there any way I can do that in laravel?
Post Model
public function scopePublished($query)
{
return $query->where('published',true);
}
Now I want to join user table with post table but in join I want to use this scope method directly but its giving me error.
Users::join('posts',function($q){
$q->on('posts.user_id','users.id');
$q->published();
})->get();
So is there any way I can use scope directly inside join subquery ?

First, you need to add the relation between posts and users to the User model like so:
User Model
public function posts()
{
return $this->hasMany(Post::class);
}
and then your scope stays as it is, and your query if you wanna get users with their published posts:
return User::with(['posts' => function ($query) {
$query->published();
}])
->get();
and if you want to get only users that have published posts:
return User::whereHas('posts', function ($query) {
$query->published();
})
->get();
Note that while with('posts') will include the related table's data in the returned collection, whereHas('posts') will not include the related table's data.
Hence sometimes you may need to call both together, I mean, only with('posts') will eager load relations (in this case posts).

Related

Laravel eloquent for four tables

I'm new to Laravel. I am developing a project. and in this project I have 4 tables related to each other
-Users
-Orders
-OrderParcels
-Situations
When listing the parcels of an order, I want to get the information of that order only once, the user information of that order once again, and list the parcels as a table under it. so far everything ok. but I also want to display the status of the parcels listed in the table as names. I couldn't add the 4th table to the query. do you have a suggestion? I'm putting pictures that explain the structure below.
My current working code is
$orderParcels = Orders::whereId($id)
->with('parcels')
->with('users:id,name')
->first();
and my 'orders' model has method
public function parcels(){
return $this->hasMany(OrderParcels::class);
}
public function users(){
return $this->hasOne(User::class,'id','affixer_id');
}
Note[edit]: I already know how to connect like this
$orderParcels = DB::table('order_parcels as op')
->leftjoin('orders as o','op.orders_id','o.id')
->leftjoin('users as u','o.affixer_id','u.id')
->leftjoin('situations as s','op.status','s.id')
->select('op.*','o.*','u.name','s.situations_name')
->where('op.orders_id',$id)->get();
but this is not working for me, for each parcels record it returns me orders and user info. I want once orders info and once user info.
Laravel provides an elegant way to manage relations between models. In your situation, the first step is to create all relations described in your schema :
1. Model Order
class User extends Model {
public function parcels()
{
return $this->hasMany(OrderParcels::class);
}
public function users()
{
return $this->hasOne(User::class,'id','affixer_id');
}
}
2. Model Parcel
class Parcel extends Model {
public function situations()
{
return $this->hasOne(Situation::class, ...);
}
}
Then, you can retrieve all desired informations simply like this :
// Retrieve all users of an order
$users = $order->users; // You get a Collection of User instances
// Retrieve all parcels of an order
$parcels = $order->parcels; // You get a Collection of User instances
// Retrieve the situation for a parcel
$situations = $parcel->situations // You get Situation instance
How it works ?
When you add a relation on your model, you can retrieve the result of this relation by using the property with the same name of the method. Laravel will automatically provide you those properties ! (e.g: parcels() method in your Order Model will generate $order->parcels property.
To finish, in this situation where you have nested relations (as describe in your schema), you should use with() method of your model to eager load all the nested relation of order model like this :
$orders = Orders::with(['users', 'parcels', 'parcels.situations'])->find($id)
I encourage you to read those stubs of Laravel documentation :
Define model relations
Eager loading
Laravel Collection
Good luck !
Use join to make a perfect relations between tables.
$output = Orders::join('users', 'users.id', '=', 'orders.user_id')
->join('order_parcels', 'order_parcels.id', '=', 'orders.parcel_id')
->join('situations', 'situation.id', '=', 'order_parcels.situation_id')
->select([
'orders.id AS order_id',
'users.id AS user_id',
'order.parcels.id AS parcel_id',
'and so on'
])
->where('some row', '=', 'some row or variable')->get();

How to use eloquent to get a value from two Has Many Relations

I have an issue where a profile can have many campaigns and also many locations.
The campaigns are linked via a pivot table but my goal is just to return all of the location ids.
Profile:
public function campaigns() {
return $this->hasMany('App\Models\Campaign', 'profile_id', 'id');
}
Campaign:
public function locations() {
return $this->belongsToMany('App\Models\Location')->withPivot('campaign_id', 'location_id');
}
Currently I am solving this by doing
$campaigns = $profile->campaigns;
[Doing a nested foreach loop and placing each ID into the array]
How would I get this via a query?
I've tried
$campaigns = $profile->campaigns()
->with('locations')
->get()
->pluck('location.id');
Well, your goal is to get information from the location, so I'd start your query with that. You can condition your query based on the relationships using the whereHas() method.
This assumes your Location has the campaigns relationship defined, and your Campaign has the profile relationship defined.
$ids = Location::whereHas('campaigns.profile', function ($query) use ($profile) {
return $query->where('id', $profile->id);
})->pluck('id');
You can read more about querying by relationships in the documentation here.

create whare clause on model attribute

How to create where clause on laravel model attribute
I have the following relation between user and books. where user hasMany books and the book model belongs to single user
I want to select all books with pages > 100 that belongs to user_id = 2
I use laravel 5.2 with mysql and defined a model for User and another model for Book
When I want to get all books for specific user, I user
return User::find(2)->books;
and this works fine. But I want to get the books where pages > 100. I use:
return User::find(2)->books->where([['pages', '>', 100], ['chapters', '>', 3]]);
but doesn't work
User model:
class User extends Authenticatable
{
public function books()
{
return $this->hasMany('App\Book');
}
}
Book model
class Book extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
I expect to get all the books with user_id = 0 and pages > 100 and chapters > 3
You'll want to access the relationship method books(), not the property books. Some quotes from the documentation:
Querying Relations
Since all types of Eloquent relationships are defined via methods, you may call those methods to obtain an instance of the relationship without actually executing the relationship queries. In addition, all types of Eloquent relationships also serve as query builders, allowing you to continue to chain constraints onto the relationship query before finally executing the SQL against your database.
Relationship Methods Vs. Dynamic Properties
If you do not need to add additional constraints to an Eloquent relationship query, you may access the relationship as if it were a property.
Example solution:
return User::find(2)
->books()
->where([['pages', '>', 100], ['chapters', '>', 3]])
->get();
Note that we're using books() to access the HasMany relationship, and using the where() query builder method on it to create a constraint. Then, in order to complete and execute the query, we call get() at the end. If you don't, you'll just return the daisy chained query builder.
Your previous code might not error, because the value returned from User::find(2)->books will be a Collection object, which actually has a where() method. It just likely didn't have any matches because of the array format you passed.
To add where clouses on related models, we can use whereHas() function.
Since you want Books, Start from Book model.
$books = Book::where([
['pages', '>', 100],
['chapters', '>', 3],
])
->whereHas('user', function($query) {
$query->where('id', 2);
})
->get();

Is there an Eloquent way of doing a leftjoin in Laravel 5.4

Is there a eloquent way to do a left join in Laravel?
We'd like to get all games and fill in the progress for each one if it exists in user_games.
Right now we've written the following solution, however this isn't eloquent at all, which we like it to be.
public function usergames($user_id) {
return DB::table('games')->leftJoin('user_games', function ($join) use ($user_id) {
$join->on('user_games.game_id', '=', 'games.id')->where('user_games.user_id', '=', $user_id); })->get();
}
DB model:
Thanks in advance!
A way to do this without you actually writing a left/inner join is to use the eloquent relationships.
In your case you will have 2 model classes: User and Game
class User extends Model {
public function games() {
return $this->belongsToMany(App\Game::class);
}
}
Now, you can access the user's games like so:
$user = App\User::find($user_id);
$usergames = $user->games; // Illuminate\Support\Collection
If you want to get a list of users with games, then look into eager loading. That would look something like this:
User::with('games')->get();
This way, Eloquent will know to lazy load the relationship meaning it will only run 2 queries. One to grab the users. and one to grab the games associated with the user, and then make them available for you in the 'games' property of the user object.

Laravel eloquent: get data with model wherePivot equal to custom field

I have an eloquent object Performer that has Albums and Albums have Images
Here is setup:
Model Performer->albums():
public function albums()
{
return $this->belongsToMany('Album','performer_albums','performer_id','album_id');
}
Model Album->images()
public function images()
{
return $this->belongsToMany('Image','album_images','album_id','image_id')->withPivot(['type','size']);
}
I have performer object stored as such:
$performer = Performer::where...->first();
Now I need to get Performer's Albums with images where size is 'large'
So to avoid nesting queries, can I use with()?
I tried
$performer->albums()
->with('images')
->wherePivot('size','large')
->get();
But laravel tells me it's trying to use wherePivot for Performer-Album relationship (M-2-M)
PS. I am also aware that I can do this,
$performer = Performer::with('albums')
->with('albums.images')
->.....-conditions for additional fields in album_images....
->get();
but question remains the same.
You need eager load constraints:
$performer->albums()
->with(['images' => function ($q) {
$q->wherePivot('size','large');
}])
->get();
And btw, no, you can't do this:
Performer::with('albums')
->with('albums.images')
->.....-conditions for additional fields in album_images....
->get();
instead you could do:
Performer::with(['albums.images' => function ($q) {
$q-> .....-conditions for additional fields in album_images....
}])->get();

Resources