Laravel eloquent search query for two foreign tables - laravel

i have a question about the code above , i want to search with criteria from 2 extra tables
I want 'charge' from charges table , 'name' from user table and also 'name' from customer table
all has binds the above query runs but the doesnt fetch data from customers->name any idea how to make it work?
public function scopeSearch($query, $val){
return $query->has('customer')
->whereHas('user', function($query) use ($val) {
$query->where('tasks','like','%'.$val.'%')
->Orwhere('name','like','%'.$val.'%');
})
->with('user')
->with('customer');
}

You can follow the documentation about adding stuff to your relation query (whereHas).
So, you should have this:
public function scopeSearch($query, $val){
return $query->with(['user', 'customer'])
->whereHas('user', function($query) use ($val) {
$query->where('tasks','like','%'.$val.'%')
->Orwhere('name','like','%'.$val.'%');
})
->whereHas('customer', function($query) use ($val) {
$query->where('name','like','%'.$val.'%');
});
}
See that you had only used whereHas for users but not customers...

Finally worked! after some research i found that the problem was my using of or statement
the code above works for me:
public function scopeSearch($query, $val){
return $query->whereHas('user', function($query) use ($val) {
$query->where('tasks','like','%'.$val.'%')
->orWhere('name','like','%'.$val.'%');
})
->orWhereHas('customer', function($query) use ($val) {
$query->where('name', 'LIKE', '%'.$val.'%');
})
->with('user', 'customer');
}

Related

Sorting eloquent model by many-to-many relationship model in Laravel

I'm building an application on Laravel 5.8 where I'm having a model named company, technical_description, state, region. A company can have many locations in many state, so company and state/region are having many-to-many relationship. So my model looks something like this:
class Company extends Model {
use SoftDeletes;
protected $guarded = [];
public function states()
{
return $this->belongsToMany('App\State', 'company_state', 'company_id', 'state_id');
}
public function regions()
{
return $this->belongsToMany('App\Region', 'company_region', 'company_id', 'region_id');
}
public function technicalDescription()
{
return $this->hasOne('App\TechnicalDescription', 'company_id', 'id');
}
}
I'm now building a data-table, where I'm having Company Name, Technical Details, State, Region as table headers. I want to sort according to these relationships, so I tried in controller:
public function companies() {
return CompanyResource::collection(
Company::when($request->name, function ($q) use($request) {
$q->where('name', 'like', '%' . $request->name .'%');
})
->join('company_technical_description', 'companies.id', '=', 'company_technical_description.company_id')
->when($request->sort_by_column, function ($q) use($request) {
$q->orderBy($request->sort_by_column['column'], $request->sort_by_column['order'] );
}, function ($q) use($request){
$q->orderBy('updated_at', 'desc');
})
->paginate();
)
}
So in this case if I want to sort with any details of technical description it will be easy by simply pushing company_technical_decription.established_date in $request->sort_by_column['column']
But in case of many-to-many relationship of state and region, I'm little stuck on how can I proceed.
Help me out with it. Thanks
I know way with join, worked for me with dynamic order for data tables.
You can try something like this:
public function companies() {
return CompanyResource::collection(
Company::when($request->name, function ($q) use($request) {
$q->where('name', 'like', '%' . $request->name .'%');
})
->select('companies.*', 's.name as state_name')
->join('company_technical_description', 'companies.id', '=', 'company_technical_description.company_id')
->join('company_state as cs', 'company_state.company_id', '=', 'companies.id')
->join('states as s', 'cs.state_id', '=', 's.id')
->when($request->sort_by_column, function ($q) use($request) {
$q->orderBy($request->sort_by_column['column'], $request->sort_by_column['order'] );
}, function ($q) use($request){
$q->orderBy('updated_at', 'desc');
})
->paginate();
)
}
I didn't test this solution but it's good for start. If you now pass state_name as argument for ordering, ordering should work. But I'm not sure in your database tables and columns so set your join to work.
I think it's good idea.
Good luck!

Laravel eloquent order by subquery

I have a problem with ordering by columns in subquery (lastname, firstname).
I already tried this code as suggested by other posts:
->with(['customer' => function ($query) {
$query->orderBy("lastname", "asc")
->orderBy("firstname", "asc");
}])
Here my full code, but it doesn't work.
return Membership::forCompany($companyId)
->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
->where(function ($query) {
$query->where('end_date', '>=', Carbon::now()->toDateString())
->orWhereNull('end_date');
})
->with('federation')
->with(['customer' => function ($query) {
$query->orderBy("lastname", "asc")
->orderBy("firstname", "asc");
}]);
Here the relationships:
In customer model I have:
public function memberships() {
return $this->hasMany('App\Models\Membership');
}
In Membership model I have:
public function customer() {
return $this->belongsTo("App\Models\Customer");
}
Try orderBy() with join() like:
$memberships = \DB::table("memberships")
->where("company_id", $companyId)
->where(function ($query) {
$query->where('end_date', '>=', Carbon::now()->toDateString())
->orWhereNull('end_date');
})
->join("customers", "memberships.customer_id", "customers.id")
->select("customers.*", "memberships.*")
->orderBy("customers.lastname", "asc")
->get();
dd($memberships);
Let me know if you are still having the issue. Note, code not tested! so you may need to verify by yourself once.

Multilevel relationship whereHas on eloquent Model in Laravel

I'd like to find
Project::with('tasks.tags')->get();
where only projects with a particular id of tag return in the result set.
For ex. I'd like to find a project with tasks and tasks with tags with only id of 1. In other words, filter the tasks return inside of the Project - Task relationship.
I have tried various ways but have failed so far.
I have tried:
$project = Project::with('tasks.tags')->whereHas('tasks', function($query){
$query->whereHas('tags', function($query) {
$query->where('id', 1);
});
})->get();
And:
$project = Project::with('tasks.tags')->whereHas('tasks', function($query){
$query->whereHas('tags', function($query) {
$query->where('tag_id', 1);
});
})->get();
This is how the relationships are setup:
In Project.php
public function tasks()
{
return $this->hasMany(Task::class, 'project_id')->setEagerLoads([]);
}
In Task.php
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable')->setEagerLoads([]);
}
Note that relationship between Task and Tags is of morphToMany.
Any pointers?
You would need to scope the eager loading as well. Something like the following should work:
$project = Project::with(['tasks.tags' => function ($query) {
$query->where('id', 1);
}])->whereHas('tasks', function ($query) {
$query->whereHas('tags', function ($query) {
$query->where('id', 1);
});
})->get();
Found the answer over here.
Project::with(['tasks' => function($q) {
$q->whereHas('tags', function($query) {
$query->where('tag_id', 1);
});
}])->get();

Eloquent - How should I make a condition in a join table

I have a tournament table.
Each tournament hasMany Championships.
I want to get the tournament that match the championshipID = 333.
So, I do it :
$tournament = Tournament::with([
'championships' => function ($query) use ($request) {
$query->where('id', '=', 333);
},
'championships.settings',
'championships.category',
'championships.tree.user1',
'championships.tree.user2',
'championships.tree.user3',
'championships.tree.user4',
'championships.tree.user5'
])->first();
Example of 1 of my relations:
public function settings()
{
return $this->hasOne(ChampionshipSettings::class);
}
Tell me if you need all, to post it.
But as I put 1 eager loading relationship, I get all my tournaments instead of getting just one.
What Am I missing???
I think you're looking for whereHas() which will allow you to filter a model based on a related model's constraints. You should also use a subquery for the nested constraints if you're getting the related model more than once to avoid query duplication like:
$tournament = Tournament::whereHas('championships', function($query) use ($championshipId) {
return $query->where('id', $championshipId);
})
->with(['championships' => function ($query) use ($request) {
$query->where('id', '=', 333)
->with([
'settings',
'category',
'tree' => function($query) {
return $query->with('user1', 'user2', 'user3', 'user4', 'user5');
}]);
}])
->first();

Laravel 4 Eager Loading constraints

I want to get all Items (topics) WITH their comments, if comments user_id = $id. I try something like this, but it isn't working. So if Item hasn't got any comment with user_id = $id, then I don't need this Item.
In DiscussionsItem model I have methode:
public function discussionsComments() {
return $this->hasMany('DiscussionsComment', 'discussionsitem_id');
}
My query in controller is like this:
$items = DiscussionsItem::whereBrandId($brand_id)
->whereBrandCountryId($country_id)
->with(['discussionsComments' => function($query) use ($id) {
$query->where('user_id', '=', $id);
}])
->whereHas('discussionsComments', function($query) use ($id) {
$query->where('user_id', '=', $id);
})
->with(['views' => function($query) use ($id) {
$query->where('user_id', $id)->count();
}])
->orderBy('created_at', 'DESC')->get();
My problem is that I get items with comments, where comments user_id != $id.
P.S. I need to take 5 comments, but I cant imagine how to do that, because ->take(5) in my eager load is not working.
You can do a custom scope, or just limit the amount returned by your relation:
public function discussionsComments() {
return $this->hasMany('DiscussionsComment', 'discussionsitem_id')
->latest()
->take(5);
}

Resources