Laravel foreach json column query - php

I am trying to run a foreach loop to query data within a json data column in my DB. I believe the foreach code is correct, but I cant retrieve data using the loop. I trying to use eloquent queries if possible.
Data stored in column named 'figuresinorder' : ["1","22","2","45"]
$items = ['1', '2', '3'];
$figures3 = customtrades::where(function ($query) use ($items) {
foreach($items as $item) {
$query->whereJsonContains('figuresinorder', "$item");
}
})
->get();

First try to remove the " surrounding $item,
$query->whereJsonContains('figuresinorder', $item);
If that doesn't work, try this instead:
$query->whereRaw('JSON_CONTAINS(figuresinorder, ?)', [$item]);

Related

Work with foreach in Laravel: delete same values

I found way to delete duplicate values in the result but it doesn't work correctly. How to fix it?
I have next code:
public function getListPositionByApplication($app_id){
// $app_id = \Request::input('app_id');
$list = SparePartApplicationPositionProvider::where('app_id',$app_id)->with(['provider','application_position'])->orderBy('apos_id')
->get();
$aa=0;
foreach ($list as $value) {
if($value->apos_id==$aa){
$value->application_position->name_detail='----';
}
$aa = $value->apos_id;
Log::info($value->apos_id);
}
return $list;
}
Log::info give next information: 26,26,26,26,26,26,27,27,27,27,27,27,28
but $value->application_position->name_detail have '----' in all cases with the exception of last value
#Hussein is right, group by the common column and don't do a foreach. Let the Eloquent DB do the heavy lifting. Notice the callback where you include your second table.
$list = SparePartApplicationPositionProvider::where('app_id',$app_id)
->with(['provider','application_position' => function ($query){
$query->groupBy('name_detail');
}])
->orderBy('apos_id')
->get();
You can try collection unique() method.
https://laravel.com/docs/master/collections#method-unique

laravel use with() , pluck() together

\App\Post :
function PostMeta(){
return $this->hasMany('App\PostMeta');
}
And my Query : ( pluck is not working) -
I need to use less database queries
$query = \App\Post
::with(array('PostMeta'=>function($query){
$query->pluck('key','value');
}));
$query->get();
I need to get title_en , But I cant use pluck here!
New Update
solved:
function get_PostMeta(){
// print_r($this->relations['PostMeta']);
return $this->relations['PostMeta'];
}
$query = \App\Post::with('PostMeta')->get();
foreach ($query as $key => $post){
$post->meta = $post->get_PostMeta()->pluck('value', 'key');
}
You can't do this while eager loading the data, but you can use collection method with the same name pluck() in the view when accessing the relation data:
{{ $post->postMeta->pluck('value', 'key') }}
In this case, you'll avoid N+1 problem and get data in the format you want.
Update
Since you want to prepare data for Vue, here's a small example of how you could iterate over the collection:
foreach ($posts as $post) {
$post->meta = $post->postMeta->pluck('value', 'key');
unset($post->postMeta);
}

Laravel - get the only item properties from collection without the foreach loop

I wonder is there a way to get an only item properties without a foreach loop. Since I have a query where in most of the cases there will be only one item in collection, and I need to change the status in the pivot table for only that case, I wonder is there some elegant way of doing this without the foreach loop. This is the case I am talking about:
$opponents = $quiz
->players()
->where('id', '!=', $player->id)
->get();
if ($opponents->count() < 2) {
$quiz->status = 'finished';
$quiz->save();
foreach ($opponents as $opponent) {
$quiz->players()->updateExistingPivot($opponent->id, ['status' => 'dropped']);
}
}
You can use the function first() like this:
$quiz->players()->updateExistingPivot($opponents->first()->id, ['status' => 'dropped']);

Symfony2 objects

I am having problem in getting data from doctrine object. When I use findOne(id) and try to access any variable like $result->getVariable() it works fine. But as soon as I use doctrine query builder and add some conditions, it says
Attempted to call method "getVariable" on class "Doctrine\ORM\QueryBuilder....
My Code is
foreach ($Ids as $Id) {
$result = $em->createQueryBuilder()->select("s")
->from("Entity", "s")
->where('s.id = :s_id')
->setParameters(array('s_id'=>$Id));
if($category)
{
$result->innerJoin('s.cat','c');
$result->where("c.primaryClassification = :category");
result->setParameter('category',$category);
}
}
The Code which is working is
foreach ($Ids as $Id) {
$em->getRepository("Entity")->findOneById($Id);
}
I think it is the difference in data returned because of different types of methods used.
Thanks in advance!
That's because the QueryBuilder is only for that, to build querys (BA-DUM-TSS).
What you need is to execute the query after you build it and set the parameter correctly for a =:
foreach ($Ids as $Id) {
$query[] = $em->createQueryBuilder()->select("s")
->from("Entity", "s")
->where('s.id = :s_id')
->setParameter('s_id', $Id))
->getQuery()
->getResult();
}
also if you are looking for an array of data, is BEST if you use the IN statement without the foreach and pass the array directly to the setParameter:
$result = $em->createQueryBuilder()->select("s")
->from("Entity", "s")
->where('s.id IN (:s_id)')
->setParameter('s_id', $Ids)
->getQuery
->getResult();
If you need more info on the query builder check the docs.

laravel foreach loop in controller

i have a problem about looping data in controller (laravel 4). my code is like this:
$owner = Input::get('owner');
$count = Input::get('count');
$product = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();
when i want to use foreach to loop for $product result with code like this:
foreach ($product->sku as $sku) {
// Code Here
}
the result is returning error
Undefined property: Illuminate\Database\Eloquent\Collection::$sku
so, i try to improvise a little with this code:
foreach ($product as $items) {
foreach ($items->sku as $sku) {
// Code Here
}
}
the code returning error like this:
Invalid argument supplied for foreach()
is there someone who could help me solve this?
This will throw an error:
foreach ($product->sku as $sku){
// Code Here
}
because you cannot loop a model with a specific column ($product->sku) from the table.
So, you must loop on the whole model:
foreach ($product as $p) {
// code
}
Inside the loop you can retrieve whatever column you want just adding ->[column_name]
foreach ($product as $p) {
echo $p->sku;
}
Actually your $product has no data because the Eloquent model returns NULL. It's probably because you have used whereOwnerAndStatus which seems wrong and if there were data in $product then it would not work in your first example because get() returns a collection of multiple models but that is not the case. The second example throws error because foreach didn't get any data. So I think it should be something like this:
$owner = Input::get('owner');
$count = Input::get('count');
$products = Product::whereOwner($owner, 0)->take($count)->get();
Further you may also make sure if $products has data:
if($product) {
return View:make('viewname')->with('products', $products);
}
Then in the view:
foreach ($products as $product) {
// If Product has sku (collection object, probably related models)
foreach ($product->sku as $sku) {
// Code Here
}
}
The view (blade template): Inside the loop you can retrieve whatever column you looking for
#foreach ($products as $product)
{{$product->sku}}
#endforeach
Is sku just a property of the Product model? If so:
$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();
foreach ($products as $product ) {
// Access $product->sku here...
}
Or is sku a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.
$allData = Model::where('status', 1)->get();
foreach ($allData as $data){
$data->status = 0;
$data->update();
}
Here every $data is single data and $allData contains full collection.
using foreach on table
for me
#foreach($products as $data)
<tr>
<td>{{$data->id}}</td>
<td>{{$data->name}}</td>
<td>{{$data->price}}</td>
</tr>
#endforeach
Edit multiple data in laravel
You can use this for updating multiple data in laravel, which i have tested it and it works for me.
also remember i used relatationship here

Categories