How can I use Laravel to do something like this:
Tables:
projects:
id,name, active
pivot table: project_users
id, project_id, user_id
If I do this, I get good results, including all users of the project
Project::with('users')->where('active', '=', 1)->get();
But how can I filter on users and on active ? something like ?
Project::with('users')->where('active', '=', 1)->where('users',=,3)->get();
or ??
Project::with('users')->where('active', '=', 1)->where('users.user_id',=,3)->get();
If you want to restrict rows in the table you are eager loading then you can add constraints to the eager load where you can perform your usual QueryBuilder operations on the $query. So in your example we can do the following:
Project::with(['users' => function($query)
{
$query->where('user_id', '=', 3);
}])->where('active', '=', 1)->get();
This is assuming active is accessible to your initial table before the eager load.
Related
I would like to know if is it possible to work in a model using query builder to make a join between 4 tables, I don't know how to use eloquent with 4 tables
this is in controller
$kurikulum = DB::table('siakad.tb_01')
->select('siakad.tb_01.*', 'siakad.krs_jadwal_aktiv.*', 'siakad.mata_kuliah.*', 'siakad.kurikulum_item.*', )
->join('siakad.krs_jadwal_aktiv', 'siakad.tb_01.staf_id', '=', 'siakad.krs_jadwal_aktiv.kdds')
->join('siakad.mata_kuliah', 'siakad.krs_jadwal_aktiv.kdmk', '=', 'siakad.mata_kuliah.kode')
->join('siakad.kurikulum_item', 'siakad.mata_kuliah.id', '=', 'siakad.kurikulum_item.mata_kuliah_id')
->get();
Please try this:
$kurikulum = DB::table('tb_01')
->select('tb_01.*', 'krs_jadwal_aktiv.*', 'mata_kuliah.*', 'kurikulum_item.*')
->join('krs_jadwal_aktiv', 'tb_01.staf_id','krs_jadwal_aktiv.kdds')
->join('mata_kuliah', 'krs_jadwal_aktiv.kdmk','mata_kuliah.kode')
->join('kurikulum_item', 'mata_kuliah.id','kurikulum_item.mata_kuliah_id')
->get();
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
Currently, we can join 2 tables like
ModelA::join('table_b', 'table_a.id', '=', 'table_b.a_id');
With this approach the default scopes on model for table_b (ie: ModelB) are not applied on query. Suppose the ModelB has SoftDeletes enabled now the above join won't include whereRaw('table_b.deleted_at IS NULL'). I know i can manualy add this using following code.
ModelA::join('table_b', function($join) {
$join->on('table_a.id', '=', 'table_b.a_id')
->whereRaw('table_b.deleted_at IS NULL');
});
I want to know if there is any method to join so that it automatically apply default scope(s) in ModeB. Something like:
ModelA::joinModel(ModelB::Class, 'table_a.id', '=', 'table_b.a_id');
I used the joinSub() function to join on a subquery. So following code worked for me:
ModelA::joinSub(ModelB::select('*'), 'table_b', function($join) {
$join->on('table_a.id', '=', 'table_b.a_id');
});
By using joinSub() I can also call other scopes on ModelB like:
ModelA::joinSub(ModelB::filterThis()->filterThat(), 'table_b', function($join) {
$join->on('table_a.id', '=', 'table_b.a_id');
});
Filter out the records on related Model, the Eloquent way -
ModelA::with('modelb')->whereHas('modelb', function($query){
$query->filterThis()->filterThat();
})->get();
Laravel QueryBuilder doesn't consider Eloquent scopes while running queries.
You can simple use Eloquent instead of Query Builder. With Eloquent it can be achieved like so:
ModelA::with('modelb')->get();
Where modelb is a HasMany relationship defined in ModelA.
The above statement will produce the following query:
select * from `modela` where `modelb`.`modela_id` in (1) and `modelb`.`deleted_at` is null
I have these tables:
products: id, name
orders: id, number
order_items: order_id, product_id
So I want to get best order products. And i make this code below.
$sales = DB::table('products')
->leftJoin('order_items','products.id','=','order_items.product_id')
->leftJoin('orders','orders.id','=','order_items.order_id')
->selectRaw('products.*, COALESCE(sum(orders.item_count),0) total')
->groupBy('products.id')
->orderBy('total','desc')
->take(6)
->get();
Please help me convert query above to eloquent. This work but I want to get products morphed images too.
Eloquent also support leftJoin, so you can do something like this:
$sales = Product::query()
->leftJoin('order_items','products.id','=','order_items.product_id')
->leftJoin('orders','orders.id','=','order_items.order_id')
->selectRaw('products.*, COALESCE(sum(orders.item_count),0) total')
->groupBy('products.id')
->orderBy('total','desc')
->take(6)
->get();
But if you mean you want to use eager load, please share your models and these relations first,
Assuming you created proper relationships in the Product model, would look something like this:
Product::with('order_items', 'orders')
->selectRaw('COALESCE(sum(orders.item_count),0) as total')
->orderByDesc('total')
->limit(6)
->get();
How to fetch data from multiple table according to id by using query builder in Laravel?
example:
I have three tables such as student,parent and teacher.Now I want to fetch data from this three tables(student,parent and teacher) according to id for editing.So how can I do that?
see bellow codes please
public function edit($id)
{
$values=DB::table("student")->find($id);
$values=DB::table("parent")->find($id);
$values=DB::table("teacher")->find($id);
return view("info", compact("values"));
}
You probably want to fetch data according to id that you have. Of course that other tables need to have foreign keys of that table>
Here is laravel documentation for joins:
https://laravel.com/docs/5.8/queries#joins
and here is example code from docs:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();