select query builder returning null - eloquent

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;

Related

PostgresPagingQueryProvider retuns 0 columns

I have a PostgresPagingQueryProvider that has a simple query
Select id from action
This is expected to return 1 column. When I run the batch I have an exception saying
PreparedStatementCallback; SQL [SELECT id FROM action WHERE 1=1 ORDER BY id ASC LIMIT 1000];
The column index is out of range: 1, number of columns: 0.; nested exception is org.postgresql.util.PSQLException:
The column index is out of range: 1, number of columns: 0.
This is the query provider:
#Bean
public PostgresPagingQueryProvider queryProvider() {
PostgresPagingQueryProvider provider = new PostgresPagingQueryProvider();
HashMap<String, Order> sorting = new HashMap<>();
sorting.put("id", Order.ASCENDING);
provider.setSelectClause("Select id");
provider.setFromClause("from action");
provider.setWhereClause("where 1=1");
provider.setSortKeys(sorting);
return provider;
}
And this is the creation of the table
CREATE TABLE action (
id int4 NOT NULL,
"timestamp" timestamp NULL,
CONSTRAINT action_pkey PRIMARY KEY (id)
);
When using the same query with ItemReader this works just fine.
Ok, I have figured it out.
The problem was that due to a copy paste of mine I setting the first variable of the query to STOPPED .
As someone might notice the query does not accept any parameters. So deleting that fixed the issue.
In addition to that I thought that the part where I pass in the HashMap of the variables was unrelated, thus it is not included in the question so I guess no one could have answered that.
I am going to leave this here as a tribute to the monumental errors and time wasting a copy paste might lead.

Eloquent default attribute values: $attributes or DB column default value?

What's the proper way to implement default values for Eloquent models?
I've configured my database tables using Laravel's migrations. Some columns have default values specified. When using these tables in conjunction with Eloquent models, different things happen depending on the selected database driver:
In MySQL, when creating a new model and saving it, a DB row is inserted having the column's default value for every attribute that was not explicitly specified. This is what I would like to happen.
In Postgres and SQLite however, this is not the case. A PDOException is thrown:
[PDOException]
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column
"some_column" violates not-null constraint
DETAIL: Failing row contains (1, 2, 3, 4, 5, 6, null, null, null, null, null, null, 7, 8, null, 9, null, null, 10, 11, 12, null).
It is clear to me that the column is not nullable and that null values are not accepted. I would expect however that the default value was inserted instead of an error being raised.
I would suggest that you create your own parent model that extends Eloquent directly, and have all of your models extend this custom parent.
In the custom parent, override the performInsert() method to remove null values just before inserting. Be sure to copy the entire method from the Eloquent source code so you don't lose any important steps in the process:
class MyModelParent extends Illuminate\Database\Eloquent\Model
{
/**
* Perform a model insert operation.
*
* #param \Illuminate\Database\Eloquent\Builder $query
* #return bool
*/
protected function performInsert(Builder $query)
{
if ($this->fireModelEvent('creating') === false) {
return false;
}
... // Be sure to copy all of it!
// This is the change you'll make. Before, it was just:
// $attributes = $this->attributes;
$attributes = array_filter($this->attributes, function($val){
return $val !== null;
});
... // Be sure to copy all of it!
return true;
}
}
performUpdate() should handle this issue fine, since it uses getDirty() to get the list of fields instead of accessing the property directly.
And while you're at it, you should consider submitting a patch to Laravel that would make the core Postgres-safe.
SQL NOT NULL Constraint
The NOT NULL constraint enforces a column to NOT accept NULL values.
you are adding a null value on NOT NULL column
it seems
http://www.w3schools.com/sql/sql_notnull.asp

Laravel insert empty value Postgress error

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,
));

how to insert null or valid value in nullable column of database in EF 4.1

I am in scenerio where I need to inset a dateTime value in the database using the EF 4.1.
DateColumn in database in Nullable.
While creating the entity i am filling it as,
DTCLOSE = referenceProblemLog.DateClosed.HasValue ?
referenceProblemLog.DateClosed.Value.ToFeedFormatString() :
System.DBNull.Value.ToString(),
where ToFeedFormatString is an extension method.
Now problem i observed is, if I have a proper value then it is inserted correctly but
when i dont have a proper date value, i want to insert NULL in database column. However EF is saving column with Empty string
I tried to change the StoreGeneratedPattern for the field to "Identity" but problem with it is, I cant assign value to DTCLose field.
How can i have both the things?
1. EF should insert NULL in database when proper value is not there
2. proper value otherwise
Please help
Thanks
Anup
This is wrong System.DBNull.Value.ToString() because at the end you will have string object, ToString() never returns null.
You have to set DTCLOSE = null
Also, with EF you don't have to use DBNull, you just define nullable property and set it null
You Can use this :
Nullable<DateTime> date=null;
var entity = new Model()
{
GoDate = date
};
DataContext.Models.Add(entity);
DataContext.SaveChanges();

zend framework check if column exist in a resultset

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,