I'm working on a small project using laravel and i would like to know how can i use WHERE clause for apartment this is my code
$buildings = Building::with('apartment')->get();
i have already tried :
$buildings = Building::with('apartment')->where('name','=',5)->get();
but it applies for Building not for apartment.
how can i apply WHERE clause for apartment ?
You can apply a Closure to with(...) if you pass in an array using the following syntax:
Model::with(['relation_name' => function ($query) { ... }])
In your case, what you're looking for is:
$buildings = Building::with(['apartment' => function ($apartments) {
$apartments->where('name', 5); // if you don't pass an operator, it's assumed to be '='.
}])->get();
You can also write it like this using PHP 7.4 shorthand closures.
$buildings = Building::with(['apartment' => fn($apartments) => $apartments->where('name', 5)])->get();
https://laravel.com/docs/7.x/eloquent-relationships#constraining-eager-loads
Try this
$buildings = App\Building::with(['apartment' => function ($query) {
$query->where('name', 5); .
}])->get();
Related
I am new to laravel and i am trying to write a query whereby the selected stock->OrderProduct->product_id is passed to get the relevant result. The query looks like this :
$stock = Stock::where('orderProductid.product_id', $pharmacyEvent->prescription->product_id)
->whereHas('orderProduct.product.prices')
->with(['orderProduct.product.price' => function ($query) use ($paymentMode) {
$query->where('scheme_id', $paymentMode->scheme_id);
}])->first();
$price = $stock->orderProduct->product->price;
This doesnt work as it is bad practise and i rewrote the query like below, which brings me wrong results.
$stock = Stock::whereHas('orderProduct.product.prices')
->with([
'orderProduct.product' => function ($query) {
$query->where('id', $pharmacyEvent->prescription->product_id);
},
'orderProduct.product.price' => function($query) {
$query->where('scheme_id', $paymentMode->scheme_id);
}
])->first();
Any advise on eloquent methods to use when i want to pass a condition based on relationships in a query will be highly appreciated. I am using lavel 5.8
I used whereHas :
$stock = Stock::whereHas('orderProduct.product', function($query) use ($pharmacyEvent) {
$query->where('id', $pharmacyEvent->prescription->product_id);
})
// ->whereHas('orderProduct.product.prices')
->with(['orderProduct.product.price' => function ($query) use ($paymentMode) {
$query->where('scheme_id', $paymentMode->scheme_id);
}])->first();
$price = $stock->orderProduct->product->price;
I'm running the following query that has a with() relation.
$logbook_objectives = self::whereIn('lobjective_id', $logbook_objectives_ids)
->with(['objective' => function($q) use ($course_objective_ids){
$q->select(['objective_id', 'objective_code', 'objective_name'])
->whereIn('objective_id', $course_objective_ids)
->whereIn('objective_parent', $course_objective_ids, 'or');
}])
->withCount(['entryObjectives' => function ($q) use ($learner_id) {
$q->where('created_by', $learner_id);
}])
->get();
Sometimes the the returned 'objective' field is null because of the rules within the with function. How do I remove the results that have objective = null?
I tried using ->whereHas('objective') before the ->get() but it doesn't change anything. Is there another way to evaluate if the with function returned null keeping the same query?
Solutions I have on my head:
Use join instead, so I can evaluate null results in the same query.
Use a foreach look verifying if the objective field is null and remove found results from my returned list.
If objective table has 'objective_id' or any other key as primary key then place that key in whereNotNull just as given below:
$logbook_objectives = self::whereIn('lobjective_id', $logbook_objectives_ids)
->with(['objective' => function($q) use ($course_objective_ids){
$q->select(['objective_id', 'objective_code', 'objective_name'])
->whereIn('objective_id', $course_objective_ids)
->whereIn('objective_parent', $course_objective_ids, 'or')->whereNotNull('objective_id');
}])
->withCount(['entryObjectives' => function ($q) use ($learner_id) {
$q->where('created_by', $learner_id);
}])
->get();
The solution I found was to use a whereHas together with the with function. The query would be:
$logbook_objectives = self::whereIn('lobjective_id', $logbook_objectives_ids)
->with(['objective' => function($q) use ($course_objective_ids){
$q->select(['objective_id', 'objective_code', 'objective_name'])
->whereIn('objective_id', $course_objective_ids)
->whereIn('objective_parent', $course_objective_ids, 'or');
}])
->whereHas('objective', function($q) use ($course_objective_ids){
$q->select(['objective_id', 'objective_code', 'objective_name'])
->whereIn('objective_id', $course_objective_ids)
->whereIn('objective_parent', $course_objective_ids, 'or');
})
->withCount(['entryObjectives' => function ($q) use ($learner_id) {
$q->where('created_by', $learner_id);
}])
->get();
In that case only rows that the objective exists will be returned.
I have the following query in my controller.
$items = Item::with(['subitems' => function($query) {
$query->where('language_id', '=', 1);
}])->get();
This is correctly getting me all items including subitems that have a language id of 1.
There are two things I would like to do with this though
Firstly, I need to return all subitems that have a distinct 'ref_id' value.
Secondly, I would like to give preference to the language id 1 but if none exist, use any language id.
So for example, I know this code won't work, but the sort of thing I am looking for is:
$items = Item::with(['subitems' => function($query) {
$subItems = $query->where('language_id', '=', 1)
->where('ref_id', 'is', 'distinct');
if($subItems->count() <= 0) {
$subItems = $query->where('ref_id', 'is', 'distinct');
}
}])->get();
Is this possible or is it a bit too complicated for Query Builder? Even if one of the two requests was possible, that would be great.
Try this:
$items = Item::with(['subitems' => function($query) {
$join = Subitem::select('ref_id', DB::raw('MIN(language_id) language_id'))
->groupBy('ref_id');
$sql = '(' . $join->toSql() . ') subitems_distinct';
$query->join(DB::raw($sql), function($join) {
$join->on('subitems.ref_id', 'subitems_distinct.ref_id')
->on('subitems.language_id', 'subitems_distinct.language_id');
});
}])->get();
We can use the fact that your preferred language_id is the lowest value and select the minimum.
Can someone show me how to write this query in Eloquent?
SELECT * FROM `projects` WHERE `id`='17' OR `id`='19'
I am thinking
Project::where('id','=','17')
->orWhere('id','=','19')
->get();
Also my variables (17 and 19) in this case are coming from a multi select box, so basically in an array. Any clues on how to cycle through that and add these where/orWhere clauses dynamically?
Thanks.
You could do in three ways. Assume you've an array in the form
['myselect' => [11, 15, 17, 19], 'otherfield' => 'test', '_token' => 'jahduwlsbw91ihp'] which could be a dump of \Input::all();
Project::where(function ($query) {
foreach(\Input::get('myselect') as $select) {
$query->orWhere('id', '=', $select);
}
})->get();
Project::whereIn('id', \Input::get('myselect'))->get();
$sql = \DB::table('projects');
foreach (\Input::get('myselect') as $select) {
$sql->orWhere('id', '=', $select);
}
$result = $sql->get();
The best approach for this case is using Laravel's equivalent for SQL's IN().
Project::whereIn('id', [17, 19])->get();
Will be the same as:
SELECT * FROM projects WHERE id IN (17, 19)
This approach is nicer and also more efficient - according to the Mysql Manual, if all values are constants, IN sorts the list and then uses a binary search.
In laravel 5 you could do it this way.
$projects = Projects::query();
foreach ($selects as $select) {
$projects->orWhere('id', '=', $select);
}
$result = $projects->get();
This is very useful specially if you have custom methods on your Projects model and you need to query from variable. You cannot pass $selects inside the orWhere method.
public function getSearchProducts($searchInput)
{
$products = Cache::rememberForever('getSearchProductsWithDiscountCalculationproducts', function () {
return DB::table('products_view')->get();
});
$searchProducts = $products->filter(function ($item) use($searchInput) {
return preg_match('/'.$searchInput.'/i', $item->productName) || preg_match('/'.$searchInput.'/i', $item->searchTags) ;
});
$response = ["status" => "Success", "data" => $searchProducts ];
return response(json_encode($response), 200, ["Content-Type" => "application/json"]);
}
use filter functionality for any customize situations.
look at code first:
$bookname = 'www';
User::with(array('roles' => function($query) {
$query->where('bookname' => $bookname);
}))->find(1);
but it lead an error"undefined variable $bookname"..how to fix this?thanks
Wrong syntax.
$bookname = 'www';
User::with(array('roles' => function($query) use ($bookname) {
$query->where('bookname', '=', $bookname);
}))->find(1);
To use the $bookname inside of the anonymous function you need to pass it using use statement. In addition where() function inside your anonymous function takes 3 parameters:
column name, comparing operator, search value.