How to order by many-to-many relationship Laravel Eloquent - php

I have many-to-many relationship users|pivot|task
I need to order records by pivot table column(role) and by user table column(name). Ordering by pivot works, but order by users doesnt. Please give any advice how to fix this
Job model
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class,'user_job')
->using(UserJob::class)
->withPivot('role')
->withTimestamps();
}
User Model
public function jobs(): BelongsToMany
{
return $this->belongsToMany(Job::class,'user_job')
->using(UserJob::class)
->withPivot('role')
->withTimestamps();
}
Repository
return User::find($dto->getUserId())
->jobs()
->where($dto->getFilters())
->with('users')
->orderBy($dto->getSortBy(),$dto->getSortType()) // need to order by users.name
->paginate($dto->getPerPage());

Related

How to search in another table in Laravel with Eloquent?

I have two models:
Order
Customer
I have customer_id in orders table. Customer details (name, phone, email etc) in customerstable. But I am writing query for orders table.
Now, I want to search with Customer Name on Orders but in Orders table I just have customer_id.
How will I link up with customers table so that I can search with Customer Name. I want to do that with Eloquent.
How is this possible?
There are multiple ways of doing relationship filtering with Eloquent.
You can achieve it with whereHas or using an advanced join / left join query.
I suggest you do a research about Eloquent filtering on Laravel documentation, everything you need for your task should be there.
https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
https://laravel.com/docs/8.x/queries#advanced-join-clauses
In models define relationships
Customer model
public function orders()
{
return $this->hasMany(Orders::class);
}
Order model
public function customer()
{
return $this->belongsTo(ustomer::class, 'foreign Key', 'id');
}
Then you can call relationships and search what you want
Customer::whereHas('orders')
First you need to create relationship in the orders model, you can use either belongsTo or hasOne relationship.
belongsTo relationship will be like as below
public function customer()
{
return $this->belongsTo(ustomer::class, 'foreign Key', 'id');
}
and the hasOne relationship will be like as below
public function customer()
{
return $this->hasOne(Customer::class, 'foreign_key', 'local_key');
}
The search function will be like as below
public function OrderSearch(Request $request){
try {
/**
* Fetching data with orders relationship
*/
$orders = OrdersModel::with(['customer'])
if(!empty($request->search)){
/**
* Searching the name key inside
* the customer relationship
*/
$orders->where(fn($query)=>
$query->whereHas('customer',fn($query2) =>
$query2->where('name','LIKE','%'.$request->search.'%'));
);
}
/**
* Returning the response
*/
return $orders->get();
} catch (\Throwable $th) {
throw $th;
}
}
Kindly refer the laravel eloquent-relationships documentation : eloquent-relationships

laravel 2 tables have 1:n relationship with the same table

I have a users table, a products table, and and an assets table. A user can have many assets, as can a product, meaning both Users, and Products have a 1:n relationship with assets. In Laravel how would show this relationship in Eloquent, is this a Polymorphic relationship, with the struct of the assets table columns being something like,
ID, type, file_path, ownable_id, ownable_type
I think your assets table columns should be
id, type, file_path, assetable_id, assetable_type
Add this relation to your user and product model
public function assets()
{
return $this->morphMany(Asset::class, 'assetable');
}
Next, add this relation to your asset model
public function assetable()
{
return $this->morphTo();
}
relation of user model
public function assets()
{
return $this->morphMany(Asset::class, 'assetable');
}
relation of asset model
public function assetable()
{
return $this->morphTo();
}

BelongsTo relation Laravel 5.4 not working

I have two models (see below). With a one to many relationship, the HasMany relationship is working as expected, but the inverse belongsTo doesn't get any results when I try to do this.
$user = Auth::user();
dd($user->location->name);
I have the following database structure
Table locations
id
name
slug
Table users
id
name
email
password
location_id
remember_token
App/User model
public function location() {
return $this->belongsTo( 'App\Models\Location' );
}
and the App\Models\Location model
public function users()
{
return $this->hasMany('App\User');
}

Eloquent ORM hasManyTrough

i have a hasManyTrough() relation in my database but could not get it to work with eloquent.
the relation in my database
category(id)
entry(id)
category_entries(category_id, entry_id)
i have 3 models
Category
has_many CategoryEntries
Entry
has_many CategoryEntries
CategoryEntry
belongs_to Category
belongs_to Entry
so every category has many entries and every entry has many categories.
in rails i would do the following
Entry
has_many CategoryEntries
has_many Categories, through: :category_entries
i have created the following in eloquent
CategoryEntry
public function category(){
return $this->belongsTo('App\Category');
}
public function entry(){
return $this->belongsTo('App\Entry');
}
Category
public function categoryEntries(){
return $this->hasMany('App\CategoryEntry');
}
Entry
public function categoryEntries(){
return $this->hasMany('App\CategoryEntry');
}
public function categories()
{
return $this->hasManyThrough('App\Category', 'App\CategoryEntry', 'category_id', 'id');
}
but this will create the following sql command:
select `entries`.*, `category_entries`.`category_id` from `entries`
inner join `category_entries` on `category_entries`.`id` = `entries`.`entry_id`
this makes no sence. where is my mistake?
As described in your question, relation is
Category (hasMany) Entry (hasMany) CategoryEntries
So we can add hasManyThrough relation in Category Model not in Entry model
class Category
.......
public function categoryEntries()
{
$this->hasManyThrough(App\CategoryEntry::class, App\Entry::class);
}
UPDATE
if the relation is based on db you have given, then you have Many-Many relation between Category and Entry. then you can have,
class Entry
....
public function categories()
{
return $this->belongsToMany(App\Category::class, 'category_entries');
}

Laravel Eloquent Relationship custom query

I have 2 tables: USERS and SUBJECTS
The relationship between USER and SUBJECT is many to many.
In the User.php and Subject.php models, I defined:
User.php
function subjects() { return $this->belongsToMany('App\User'); }
Subject.php
function users() { return $this->belongsToMany('App\Subject'); }
The pivot table is subject_user and it has 3 columns:
subject_id, user_id, finished
The finished value can only be between 0 and 1.
Now I know that when I want to select all the subjects that an user studied, I have to write $user->subjects.
But what if I want to select all the subjects that an user studied and the finished value in the pivot table is equal to 1?
You need to add "withPivot()" to your relationship definitions, like this:
function subjects() { return $this->belongsToMany('App\User')->withPivot('finished'); }
function users() { return $this->belongsToMany('App\Subject')->withPivot('finished'); }
Then you can do:
$user->subjects()->where('finished', 1)->get();
You will need to eager load that relationship and use the wherePivot method.
$user = User::with(['subjects' => function($q) {
$q->wherePivot('finished', 1);
}])->fine($user_id);

Categories