When creating elements in Laravel 4 using the ORM like so:
FigureModel::create( array( 'numericFieldOne'=>1, 'numericFieldTwo'=> null ) );
FigureModel::create( array( 'numericFieldOne'=>1, 'numericFieldTwo'=> '' ) );
In mysql all is well and all the items are perfect inserterd, no problem so far:
But in postgress, it tries to insert empty values without a quote making postress crash. Like so:
What to do?? Does anyone have an idea about how to tackle this problem? Thanks!!
( and custom setters for each element validating it to be a number or null is not an option )
#pozs Thanks! since you pointed out that the correct error should be a 42601 im once again confidant that the prostgress adapter for this orm is sound.
The solution:
In my case i just have to create setter functions for all the numeric null values in the database something like this
public function setNumericFieldAttribute($var){
$this->attributes['numericField'] = empty($var) ? null : $var;
}
This way the value is always null or a value
Thanks!!
It seems Laravel's debug screen cheats you: if the query really was that, the postgres error would be syntax error at or near "," with SQL state 42601
The problem is, postgres does not accept '' (the empty string) as a valid representation for an integer.
Use one of 0, '0', like:
FigureModel::create(array('worldwideoffices' => 1, 'worldwideemployees' => 0));
FigureModel::create(array('worldwideoffices' => 1, 'worldwideemployees' => '0'));
But preferably use null if it makes more sense.
Note: if you insert data from another source, just use casting to integer in php:
FigureModel::create(array(
'worldwideoffices' => (int) $offices,
'worldwideemployees' => (int) $employees,
));
Related
Will laravel 8's withSum function supports default value?
use App\Models\Post;
$posts = Post::withSum('comments', 'votes')->get();
In this relation laravel returns 'comments_sum_votes' as null if a 'post' has no 'comments'.Can we set it to return 0?
I just bumped into this.
While an eloquent accessor may work in certain situations, doing ORDER BY or GROUP BY on this column still wouldn't return correct results (because the database query would still return null when no records are found).
Alternatively, you could do COALESCE yourself like so, which is more efficient:
$post = Post::query()
->withSum([
'comments' => fn ($query) => $query->select(DB::raw('COALESCE(SUM(votes), 0)')),
], 'votes')
->get();
Ref
I'm new to Laravel and I'm trying to retrieve the id value of a selected row using query builder but it's not working. I've tried it in many ways according to the Laravel documentation and I still have a problem. I think it's related to the use of a variable but I don't know how to fix it.
public function submit_idea(Request $request)
{
$key=$request->input('key');
$workshop_id= DB::table('workshops')->where('autokey',$key)->value('id');
$id = auth()->User()->id;
$idea=new Idea;
$idea->title=$request->input('title');
$idea->description=$request->input('description');
$idea->user_id=$id;
$idea->workshop_id=$workshop_id;
$idea->save();
return view('submit_idea');
}
the error i'm getting is:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'workshop_id' cannot be null (SQL: insert into ideas (title, description, user_id, workshop_id) values (ppp, iiuu, 7, ?))
Can anyone help me, please?
Change:
$workshop_id = DB::table('workshops')->where('autokey',$key)->value('id');
To:
$workshop_id = DB::table('workshops')->select('id')->where('autokey',$key)->first();
By the way, the errors means that the workshop_id can't be null. If it can be null, be sure to add nullable() to the column in your migration file.
You can also working with
$workshopId = DB::table('workshops')->where('autokey', $key)->first()->pluck('name');
echo $workshopId;
Created a migration with a new field of jsonb type, not null and default value = []. (example of stored data: ["235", "214"]) and add a rule to model [['unique_users'], 'safe']
public function up()
{
$connection = Yii::$app->getDb();
$sql = 'ALTER TABLE offer ADD unique_users jsonb not null default \'[]\'';
$command = $connection->createCommand($sql, []);
$command->queryAll();
}
Result: Added a unique_users field with a default value [] to each row. jsonb_typeof(unique_users) returns an array type.
Created needed query for test
select jsonb_array_length(unique_users) from test where unique_users #> '"19"'::jsonb
Result from PgAdmin:
It seemed that everything was ready. But after saving a new record with Yii2, I received a query error:
ERROR: you can not get the length of a scalar
And I saw that another value was recorded in the field - ""
I was tryed to add the validation rule to Model: ['unique_users', 'default', 'value' => '[]'],.
Result:
...with the same problem of query - value is not an array. jsonb_typeof(unique_users) returns an string type.
How to insert empty array into jsonb column?
I think you're accidentally sending an empty string as the value for your unique_users field. If the value would be completely empty it should take the default DB value for the column. Please make sure the unique_users field is completely empty (null) when saving.
You can however also do this with a default value rule. This should do the trick:
['unique_users', 'default', 'value' => json_encode([])],
['unique_users', 'default', 'value' => []],
If I do this...
Context.Orders.Select(o => o.User.UserId);
... I get an exception because User is null. I can use Include instead,
Context.Orders.Include(o => o.User).Select(o => o.User.UserId);
... but shouldn't User be loaded automatically?
EDIT:
The first snippet of code doesn't work when the Select is applied to the result of a function. Which type should the function return in order to tack the Select onto the database query?
I've tried IEnumerable<Order> and IQueryable<Order>.
I have this query for example:
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$query_Group = $dbAdapter->select();
$query_Group->from(array('FI' => 'request_field'),
array('*'));
$resultRows = $dbAdapter->fetchAll($query_Group);
Ok, now how can I know if inside $resultRows there is the column "Label" for example?
I know I can do that:
foreach($resultRowsas $key => $Field)
{
if(isset($Field['Label'])
{ .... }
}
But if is possible I want it to know without loop it....
It is possible?
Thanks again....
$Field['Label'] will always be set. It may be empty, but will always be set!
if you want all records where the value is NULL, change your query appropriately
If I understood correctly, you want to know whether a given column exists in the table. In that case, you might call the describeTable() method for this.
You can see a description in the Zend_Db_Adapter documentation.
If the column is defined in the table schema, then you need to query for an appropriate value, like NULL, as #JellyBelly says. In this case, his answer is what you need.
Hope that helps,