My whereJsonContains not working (Laravel 5.8) - php

I have problem with my laravel query.
Now I use query like this:
$courses = Course::whereJsonContains('schedule->day', 1)->get();
It doesn't work.
I'm using postgreSql 9.6 and my database and raw query look like this
http://sqlfiddle.com/#!17/88fd2/1/0
I want to select class where have schedule in day = 1

If you define the column as schedule->day, MySQL assumes that this is an array of integers. In your case it's an array of objects, so you have to target the parent array and add the property name you are looking for in the second argument.
Like so:
$courses = Course::whereJsonContains('schedule', ['day' => 1])->get();

I solved with
$courses = Course::whereJsonContains('schedule', [['day' => '1']])->get();

I solved with
$products=ProductShop::active()
->whereJsonContains('tag', [['value' => "tampa"]])->get();

If you're querying the value уоu don't need to use whereJsonContains, simply use a regular where query such as:
$courses = Course::where('schedule->day', 1)->get();`
If you want to check if day exists in Json, use whereJsonLength such as:
$courses = Course::whereJsonLength('schedule->day', '>', 0)->get();

Related

WhereIn Inside ->where() array - Laravel Query Builder

I'm trying use a whereIn inside a where array I am passing to Laravel query Builder:
$where = [['Participants.Client_Id','IN', $clientId]];
DB::table('Participants')->where($where)->get()
Something like is what I want to achieve, and I know there are works around such as using whereIn, but I'm sharing here a small piece of code to give you an idea, so I need to change the array to make it works as a whereIn, not changing the ->where to ->whereIn or ->whereRaw
DB::table('participants)->whereIn('Participants.Client_Id',$clientId)->get();
You must collect the IDs in the $clientId variables.
If I understand, you could do something like that :
$wheres = [['Participants.Client_Id','IN', [$clientId]]];
$query = DB::table('Participants');
foreach($wheres as $where) {
$query->where($where[0], $where[1], $where[2]);
}
$participants = $query->get();
As laravel document , you can use array in where and each element of this array must be a array with three value . So your $where variable is correct.
But as I searched in operator is not supported by query builder of where.

Need help for my sql query to make use of AS operator [duplicate]

Lets say we are using Laravel's query builder:
$users = DB::table('really_long_table_name')
->select('really_long_table_name.id')
->get();
I'm looking for an equivalent to this SQL:
really_long_table_name AS short_name
This would be especially helpful when I have to type a lot of selects and wheres (or typically I include the alias in the column alias of the select as well, and it gets used in the result array). Without any table aliases there is a lot more typing for me and everything becomes a lot less readable. Can't find the answer in the laravel docs, any ideas?
Laravel supports aliases on tables and columns with AS. Try
$users = DB::table('really_long_table_name AS t')
->select('t.id AS uid')
->get();
Let's see it in action with an awesome tinker tool
$ php artisan tinker
[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});
// NULL
[2] > DB::table('really_long_table_name')->insert(['id' => null]);
// true
[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
// array(
// 0 => object(stdClass)(
// 'uid' => '1'
// )
// )
To use aliases on eloquent models modify your code like this:
Item
::from( 'items as items_alias' )
->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
->select( DB::raw( 'items_alias.*' ) )
->get();
This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result.
Adding DB::raw prevents laravel from adding table prefixes to aliases.
Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.
$products = DB::table('products AS pr')
->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
->orderBy('pr.id', 'desc')
->get();
Hope this helps.
To use in Eloquent.
Add on top of your model
protected $table = 'table_name as alias'
//table_name should be exact as in your database
..then use in your query like
ModelName::query()->select(alias.id, alias.name)
You can use less code, writing this:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name'));
And of course if you want to select more fields, just write a "," and add more:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));
This is very practical when you use a joins complex query
I have tried all these options and none works for me. Then I had found something in the Laravel documentation that really works.
You could try this:
DB::table('table_one as t1')
->select(
't1.field_id as id','t2.field_on_t2 as field'
)->join('table_two as t2', function ($join) {
$join->on('t1.field_id ', '=', 't2.field_id');
})->get()
Also note that you can pass an alias as the second parameter of the table method when using the DB facade:
$users = DB::table('really_long_table_name', 'short_name')
->select('short_name.id')
->get();
Not sure if this feature came with a specific version of Laravel or if it has always been baked in.
Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'",
just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')
In the latest version of Laravel 9, you can use alias name for column as:
$events = Booking::whereBetween('sessionDateTime', [$today, $nextMonth])->get(['bookings.sessionDateTime as start']); // start is an alias here

Laravel 5.2 - Change Data Format get from Eloquent

I have a model like this-
$feature_project = FeatureProject::select('feature_id')
->where('project_id', $project->id)
->get();
And if I return it, I am getting a output like this-
[
{
"feature_id": 2
},
{
"feature_id": 4
},
{
"feature_id": 9
}
]
But I want t output like this-
[2,4,9]
So I need to convert the output.
But I am not finding a way without using for-each loop (make a temp array, push all elements to that array from current array with a for-each loop).
But I think there is more smart way than that in Laravel to do that.
I think Laravel Collection is used for this purpose.
You can call pluck() method on the query builder.
$feature_project = FeatureProject::select('feature_id')
->where('project_id', $project->id)
->pluck('feature_id'); // [2,4,9]
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_lists
Alternatively, you can use PHP's array_column() function for raw arrays.
http://php.net/manual/en/function.array-column.php
In Laravel's collections, you can call a method called Flatten, which flattens a multi-dimensional collection into a single dimension.
https://laravel.com/docs/5.2/collections#method-flatten
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['taylor', 'php', 'javascript'];
With a fairly flat object, it should return just the values.
Use pluck():
$feature_project = FeatureProject::where('project_id', $project->id)->pluck('feature_id');
An alternative way also will be helpful in some cases.
We can run raw queries inside select function.
Here is an example:
$feature_project = FeatureProject::select(DB::raw('GROUP_CONCAT("feature_id")))
->where('project_id', $project->id)
->get();
In DB::raw we can run mysql query with function and case same as mysql query.
You can use lists() and toArray() :
$feature_project=FeatureProject::where('project_id', $project->id)->lists('id')->toArray();
Hope this helps.

Laravel modifying multiple rows at once

I have an array of $ids.
I'd like to essentially say:
foreach($ids as $id):
$user = User::find(1);
$user->life_expectancy -= 1;
$user->save();
endforeach;
Except I have thousands of ids in the array, and I'd much rather do something like:
$users = User::whereIn('id', $ids)->update(array('life_expectancy' => --1));
To just get it done in a single query. But that isn't going to work... is there another method?
I know I can update multiple users to all have the same life_expectancy, but I'd like it to be a modification of the previous value.
Check out this site, http://community.sitepoint.com/t/one-sql-statement-to-subtract-and-update-a-field-value/4673 if you decide to use a raw query, but looking on laravel's docs I think you can just do this,
$users = DB::table('users')
->whereIn('id', $ids)->decrement('life_expectancy');
App\User::whereIn('id',[1,2])->decrement('life_expectancy');
If you need -2 use next string:
App\User::whereIn('id',[1,2])->decrement('life_expectancy',2);

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Lets say we are using Laravel's query builder:
$users = DB::table('really_long_table_name')
->select('really_long_table_name.id')
->get();
I'm looking for an equivalent to this SQL:
really_long_table_name AS short_name
This would be especially helpful when I have to type a lot of selects and wheres (or typically I include the alias in the column alias of the select as well, and it gets used in the result array). Without any table aliases there is a lot more typing for me and everything becomes a lot less readable. Can't find the answer in the laravel docs, any ideas?
Laravel supports aliases on tables and columns with AS. Try
$users = DB::table('really_long_table_name AS t')
->select('t.id AS uid')
->get();
Let's see it in action with an awesome tinker tool
$ php artisan tinker
[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});
// NULL
[2] > DB::table('really_long_table_name')->insert(['id' => null]);
// true
[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
// array(
// 0 => object(stdClass)(
// 'uid' => '1'
// )
// )
To use aliases on eloquent models modify your code like this:
Item
::from( 'items as items_alias' )
->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
->select( DB::raw( 'items_alias.*' ) )
->get();
This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result.
Adding DB::raw prevents laravel from adding table prefixes to aliases.
Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.
$products = DB::table('products AS pr')
->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
->orderBy('pr.id', 'desc')
->get();
Hope this helps.
To use in Eloquent.
Add on top of your model
protected $table = 'table_name as alias'
//table_name should be exact as in your database
..then use in your query like
ModelName::query()->select(alias.id, alias.name)
You can use less code, writing this:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name'));
And of course if you want to select more fields, just write a "," and add more:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));
This is very practical when you use a joins complex query
I have tried all these options and none works for me. Then I had found something in the Laravel documentation that really works.
You could try this:
DB::table('table_one as t1')
->select(
't1.field_id as id','t2.field_on_t2 as field'
)->join('table_two as t2', function ($join) {
$join->on('t1.field_id ', '=', 't2.field_id');
})->get()
Also note that you can pass an alias as the second parameter of the table method when using the DB facade:
$users = DB::table('really_long_table_name', 'short_name')
->select('short_name.id')
->get();
Not sure if this feature came with a specific version of Laravel or if it has always been baked in.
Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'",
just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')
In the latest version of Laravel 9, you can use alias name for column as:
$events = Booking::whereBetween('sessionDateTime', [$today, $nextMonth])->get(['bookings.sessionDateTime as start']); // start is an alias here

Categories