I want to do filter in laravel eloquent for the inner tables, i have 3 tables, discover, category and subcategory, discover have category and subcategory id, if someone try to filter with any text name, i want to filter from all that 3 tables, i am not able to find, how to filter from category and subcategory table, here is my code, can anyone please help me to resolve this issue ?
$discover = Discover::with(['category','subcategory'])->where('status','1')->where('name','like',"%{$searchString}%")->orWhere('description','like',"%{$searchString}%")->orderBy('created_at', 'DESC')->get()->toArray();
You can do this If you want to filter from child table also
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
$discover = Discover::where('status', '1')
->where('name', 'LIKE', "%$searchString%")
->orWhereHas('category', function ($query) use ($searchString) {
return $query->where('name','LIKE', "%$searchString%");
})
->orderBy('created_at', 'DESC')
->get();
you can constrain eager loading in this way:
Discover::with([
'category' => function($query){
return $query->where('name','your-category-name');
}
])->whereHas('category', function($query) {
return $query->where('name','your-category-name');
});
the same applies for other relationships. Further info can be found on the laravel docs.
has whereHas Or WhereRelation relation
if you need OrderBY on relation tables
then you need to do join
Related
I have two Model named Product and Category. Admin can change the status of Product and Category.
Here Product and Category has many to many relations. So that, all Product can belongs to multiple Category
Now at my user panel,
I want to show that all Product whose all Category's status is active.
you can do this in your product model
public function categories(){
return $this->belongsToMany(Category::class, CategoryProduct::class, 'product_id', 'category_id');
//->withPivot([]); if you need anything from the pivot table for any reason you can add the column names in the array
}
this is assuming that the pivot table have the columns product_id and category_id
$products = Product::with('categories')
->whereHas('categories', function ($query) {
$query->where('categories.status', 'active');
})
->get();
inside the where the word categories is the table name
The solution is:
$products = Product::with('category')
->whereHas('category', function ($query) {
$query->where('status', 'active'); // use your column & condition
})
->get();
It works for me, got all the products that have all the categories active. First time I thought complicated so I didn't solve.
$products = Product::whereDoesntHave('catagories',function($category){
$category->where('status','!=',1);
});
$subTasks = SubTask::with(['task'])
->with(['users.subTaskInfos' => function ($q) {
$q->orderBy('created_at', 'desc');
$q->where('sub_task_id', '=', ?);
}])
->where('active', 1)
->get();
I want to pass Base Model SubTask id in question mark section to filter out relations data and relation collection of data. Can anyone help?
One way to achieve what you are attempting is to lazy eager load users.subTaskInfos - keeping the number of queries the same
$subtasks = SubTask::with(['task'])->where('active', 1)->get();
$subtasks->load(['users.subTaskInfos' => function($q) use($subtasks) {
$q->whereIn('sub_task_id', $subtasks->pluck('id')
->orderByDesc('created_at');
});
can someone please tell me, why i am not able to select section from sections table using left join. i want list of teachers in a table, i am able to access all data from teachers table, but i am not able to see sections using left join.
Teacher Table have section_id column, which should access data from sections table on section column.
right now it is giving error when i try to fetch data in view using {{$teacher->section}} Below is my code.
public function listteachers(Request $request)
{
$teachers = DB::table('teachers')
->select('teachers.*')
->leftjoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();
return view('teachers.list',compact('teachers'));
}
You need to select the columns you want from the sections table in your query.
For example:
$teachers = DB::table('teachers')
->select('teachers.*', DB::raw('sections.name as section_name'))
->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();
Change the code to the following
$teachers = DB::table('teachers')
->select('teachers.*','sections.name as section_name')
->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();
I am testing eloquent for the first time and I want to see if it suit my application.
I have Product table:
id, name
and model:
class Produit extends Eloquent {
public function eavs()
{
return $this->belongsToMany('Eav')
->withPivot('value_int', 'value_varchar', 'value_date');
}
}
and eav table:
id, name, code, field_type
and pivot table:
product_id, eav_id, value_int, value_varchar, value_date
class Eav extends Eloquent {
public function produitTypes()
{
return $this->belongsToMany(
'ProduitType'
->withPivot('cs_attributs_produits_types_required');
}
All this is working.
But I want to search in that relashionship:
e.g: all product that have eav_id=3 and value_int=3
I have tested this:
$produits = Produit::with( array('eavs' => function($query)
{
$query->where('id', '3')->where('value_int', '3');
}))->get();
But I get all the product, and eav data only for these who have id=3 and value_int=3.
I want to get only the product that match this search...
Thank you
I know the question is very old. But added the answer that works in the latest versions of Laravel.
In Laravel 6.x+ versions you can use whereHas method.
So your query will look like this:
Produit::whereHas('eavs', function (Builder $query) {
// Query the pivot table
$query->where('eav_id', 3);
})->get()
My suggestion and something I like to follow is to start with what you know. In this case, we know the eav_id, so let's go from there.
$produits = Eav::find(3)->produits()->where('value_int', '3')->get();
Eager loading in this case isn't going to save you any performance because we are cutting down the 1+n query problem as described in the documentation because we are starting off with using find(). It's also going to be a lot easier to read and understand.
Using query builder for checking multiple eavs
$produits = DB::table('produits')
->join('eav_produit', 'eav_produit.produit_id', '=', 'produits.id')
->join('eavs', 'eavs.id', '=', 'eav_produit.eav_id')
->where(function($query)
{
$query->where('eav_produit.value_int','=','3');
$query->where('eavs.id', '=', '3');
})
->orWhere(function($query)
{
$query->where('eav_produit.value_int','=','1');
$query->where('eavs.id', '=', '1');
})
->select('produits.*')
->get();
Making it work with what you already have...
$produits = Produit::with( array('eavs' => function($query)
{
$query->where('id', '3')->where('value_int', '3');
$query->orWhere('id', '1')->where('value_int', '1');
}))->get();
foreach($produits as $produit)
{
if(!produit->eavs)
continue;
// Do stuff
}
From http://four.laravel.com/docs/eloquent:
When accessing the records for a model, you may wish to limit your results based on the existence of a relationship. For example, you wish to pull all blog posts that have at least one comment. To do so, you may use the has method
$posts = Post::has('comments')->get();
Using the "has()" method should give you an array with only products that have EAV that match your criteria.
$produits = Produit::with( array('eavs' => function($query)
{
$query->where('id', '3')->where('value_int', '3');
}))->has('eavs')->get();
I got product and stocks table;
products
id int
name varchar
created_at timestamp
stocks
id int
name varchar
product_id varchar
created_at timestamp
Product Model
public function validStock() {
return $this->hasMany('Stock')->where('quantity', '>', 10);
}
If both have created_at, how to order by stocks's created_at, I've tried two methods and it's not work
Product::with('validStock')->orderBy('validStock.created_at', 'DESC');
Product::with(array('validStock' => function($q) {
$q->orderBy('created_at', 'DESC');
}));
Instead of sorting after retrieving all data (which is impossible to do in an efficient way when paginating results) you can use a join.
(This answer is based on this one.)
Product::with('validStock')
->join('stocks', 'stocks.product_id', '=', 'products.id')
->select('products.*') // Avoid selecting everything from the stocks table
->orderBy('stocks.created_at', 'DESC')
->get();
The only thing I don't like about this is that it takes away some of the database abstraction, in that you have to write your table names here.
Note that I haven't tried this with a hasMany relationship in this direction, as you have it in your example (selecting products, and each product has many stocks). I've tried only with the hasMany in the other direction (eg selecting stocks, each of which has exactly one product).
You can not apply an order while querying an eagerly loaded relationship in Laravel. You can order the Collections after the query has been performed.
$products = Product::with(array('validStock'))
->get()
->each(function ($product)
{
$product->validStock = $product->validStock
->sortBy(function ($validStock)
{
return $validStock->created_at;
})
->reverse();
});
You should return $q in the closure:
Product::with(array('validStock' => function($q) {
return $q->orderBy('created_at', 'DESC');
}));