app/models/Model.php:
<?php
class Model extends Eloquent {
public function maker()
{
return $this->belongsTo('Maker', 'maker_id', 'id');
}
}
?>
I want to perform a search. The user enters the name of the model and the search should return the maker of that model (each model belongs to a certain maker). The following piece of code doesn't work:
$result = Model::where('title', 'LIKE', '%test%')->maker()->paginate(10);
It gives me the following error:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::maker()
Any ideas?
I've solved my own problem.
$result = Model::where('models.title', 'LIKE', $query)
->leftJoin('makers', 'models.maker_id', '=', 'makers.id')
->orWhere('makers.title', 'LIKE', $query)
->groupBy('makers.title')
->paginate(10);
According to your solution:
// $search is the keyword to find
Model::with(['maker' => function ($q) use ($search) {
$q->where('title', 'like', "%{$search}%"); // where on makers table
}])->where('title', 'like', "%{$search}%") // where on models table
->paginate(10);
This will return Models that match where clause, with related Makers, but only those who match the where clause too.
But what you need is probably this (according to your question):
Model::with('maker')->where('title', 'like', "%{$search}%") // where on models table
->paginate(10);
This on the other hand returns the Models that match the where clase, each with related Maker
Note: namespace that Model class so it won't collide with Illuminate\Database\Eloquent\Model (which it extends aliased as Eloquent)
Related
I have query with this relationships
$query = ExtraDay::with([
'credit.client'
]);
Now i am going to make searchfield filter for 'name' field which is in CLIENT model. ExtraDay model is connected to Client model via Credit model. Below there is a way how to make search for one level relationship like with(['client']);
$query->where('name', 'like', "%$q%")->whereHas('client', function
($organization) use ($q) {
$organization->where('name', 'like', "%$q%")
->orWhere('short_name', 'like', "%$q%");
But i have with(['credit.client']); How to search field 'name' in this situation?
whereHas works with nested relations, so use the same dot notation credit.client. For example:
ExtraDay::whereHas('credit.client', function ($client) use ($q) {
$client->where('name', 'like', "%$q%");
})->get();
Suppose I have a Model called 'Commodity' which has category_id belongs to a category.
In Commodity.php I defined this relationship:
public function category(){
return $this->belongsTo('App\Category');
}
Now, I want to find the commodities which their category name include 'glass'
I tried this:
$items = Commodity::orderBy('id', 'desc')->category()->where('title', 'LIKE', '%glass%');
But it populates this error:
Call to undefined method Illuminate\Database\Query\Builder::category()
Please read official documentation that covers querying relations.
Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query. Here's an example:
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
So, regarding your question I'd suggest to try next:
$commodities = App\Commodity::with(['category' => function ($query) {
$query->where('title', 'like', '%glass%');
}])->orderBy('id', 'desc')->get();
I know where the following error is coming from but I do not know how to fix it.
The error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'expenses.date' in 'where clause' (SQL: select count(*) as aggregate from expenses_sections where expenses.date LIKE %2015-12%)
What is causing it (in my controller):
if($view === 'section') {
$query = Section::query();
$query->with(['expenses' => function($query) use ($search){
$query->where('date', 'LIKE', '%2015-' . $search . '%')->get();
}]);
}
I have a select menu which I use to change the layout of the page. I have another select menu which I use to display results from a certain month only. The above error is what I am getting when I select a month, because the query is looking in the wrong table (because of the above code). The results are displayed using a relation between Expenses and Sections. What I basically want is to search for results in the expenses table, instead of the expenses_sections table, ofcourse without breaking the relation, because based on the relation, my layout is being displayed.
Expense Model:
class Expense extends Model
{
public function section()
{
return $this->belongsTo('App\Http\Models\Expenses\Section');
}
}
Section Model:
class Section extends Model
{
public function expenses()
{
return $this->hasMany('App\Http\Models\Expenses\Expense');
}
}
Query constraints should always return the query builder instance. You should not call get within your closure so try fixing it like this:
$query = Section::query();
$query->with(['expenses' => function($query) use ($search) {
$query->where('date', 'LIKE', '%2015-' . $search . '%');
}]);
This will fetch all sections and eager load the relationships. The ones that don't fit the constraints will just have an empty expenses relationship. If you only want sections that fit the constraints, then you should use whereHas method.
$query = Section::query();
$query->with('expenses')->whereHas('expenses', function($query) use ($search) {
$query->where('date', 'LIKE', '%2015-' . $search . '%');
});
I'm trying to get a simple list of products with a given category, using Laravel 5's (L5) Model::with() method. But it seems that L5 ignores the category where clause.
The relation in my Product model:
public function categories(){
return $this->belongsToMany('App\Category', 'categories_products');
}
In my Controller:
public function getByCategory($slug){
$return = Product::with(array('categories' => function($query) use ($slug){
$query->where('slug', 'like', $slug);
}))->paginate(60);
dd($return);
}
The result is a list of every product in my database, instead of just a list of those with the given category slug.
I'v tried to hardcode in some different where clauses, but all seems to be ignored. Am I missing something?
Eloquent doesn't use joins to query related data when using with(), but instead uses separate queries. In your example, it first fetches products and then fetches related categories.
You need to use has() or whereHas() to return only those products that have categories (slugs?).
public function getByCategory($slug){
$return = Product::has('categories')->with(array('categories' => function($query) use ($slug){
$query->where('slug', 'like', $slug);
}))->paginate(60);
dd($return);
}
Or:
public function getByCategory($slug){
$return = Product::whereHas('categories', function($query) use ($slug){
$query->where('slug', 'like', $slug);
})->paginate(60);
dd($return);
}
whereHas() adds a subquery that counts the number of relations. You should use DB::getQueryLog() to see the SQL that Eloquent produces. Makes it a lot easier to figure out what's going on!
Do you need to have an advanced subquery? If slug is defined as a column in product you can do this:
$return = Product::where('slug', 'like', $slug)->paginate(60);
dd($return);
Or if using the relations your query would look like this:
$return = Product::where('slug', 'like', $slug)->categories->paginate(60);
dd($return);
I am unable to filter the contents of groups table with respect to username in users table using Eager Load Constraints
public function username()
{
return $this->belongsTo('User','fk_users_id')->select(['id','username']);
}
I have tried using the code below but it filters only the users data not the groups data
$groups = Groups::with(array('username' => function($query) use ($keyword)
{
$query->where('username', 'like', '%'.$keyword.'%');
}))
->where('status',1)->paginate($paginateValue);
any help is welcome...
Think it should be something like this:
Groups::with('User')->whereHas('User', function($q) use ($key){
$q->where('username', 'like', '%'.$key.'%');
})->where('status', 1)->paginate($pagVal);