I saw similar questions but non of them work for me. This is the Transition model
class Transition extends Model
{
protected $fillable = ['origin_x', 'origin_y', 'destination_x', 'destination_y', 'freight_id', 'status', 'receiver_name', 'receiver_mobile', 'receiver_address'];
protected $table = 'freight_transitions';
}
and this is the insertion code
$transition = Transition::create([
'origin_x' => $redis['origin_x'],
'origin_y' => $redis['origin_y'],
'destination_x' => $redis['destination_x'],
'destination_y' => $redis['destination_y'],
'freight_id' => $freight->id,
'status' => 2,
'receiver_name' => $redis['receiver_name'],
'receiver_mobile' => $redis['receiver_mobile'],
'receiver_address' => $redis['receiver_address']
]);
I am sure the array of $redis` has value. But this is the error
General error: 1364 Field 'origin_x' doesn't have a default value (SQL: insert into freight_transitions (updated_at, created_at) values (2019-11-02 16:42:58, 2019-11-02 16:42:58))
From what I see, the Laravel does not try to insert the origin_x and other fields in to the DB. it only inserts the created_at and updated_at. I have a similar model called Freight, in a few lines above this code, I insert records in the same way with no error. But I don't know why it only inserts the created_at and updated_at.
I also tried
$transition = new Transition([....]);//array of above data
$transition->save();
It also generates the same error.
This is the migration
Schema::create('freight_transitions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('origin_x');
$table->string('origin_y');
$table->string('destination_x');
$table->string('destination_y');
$table->string('receiver_name')->nullable();
$table->string('receiver_mobile')->nullable();
$table->string('receiver_address')->nullable();
$table->bigInteger('freight_id')->unsigned();
$table->foreign('freight_id')->references('id')->on('freight_freights')->onDelete('cascade');
$table->enum('status', ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14'])->default(1);//1: start
$table->timestamps();
});
and this is redis array in json format
{
"origin_x": "555",
"origin_y": "666",
"destination_x": "777",
"destination_y": "8888",
"freight_type_id": "1",
"title": null,
"description": null,
"price": 130000,
"features": "2",
"services": "2,5",
"vehicle_id": 1,
"token": "111111",
"payment_type": "3",
"user_id": 1,
"receiver_name": null,
"receiver_mobile": null,
"receiver_address": null,
"payment_status": 1,
"status": 2
}
Thanks in advance.
I tried to insert data as follows
$transition = new Transition;
$transition ->origin_x = $redis['origin_x'];
$transition ->origin_y = $redis['origin_y'];
$transition ->destination_x = $redis['destination_x'];
$transition ->destination_y = $redis['destination_y'];
$transition ->freight_id = $freight->id;
$transition ->status = 2;
$transition ->receiver_name = $redis['receiver_name'];
$transition ->receiver_mobile = $redis['receiver_mobile'];
$transition ->receiver_address = $redis['receiver_address'];
$transition->save();
Even though it works, but it is still a question to me why the codes I use for tons of projects doesn't work here :|
Did you convert your json into array if not convert it into array using json_decode function of php and try again. if possible then give default value to your columns.
Related
I am trying to update multiple rows using this code:
$data = [];
foreach ($projectFieldOptions as $mapping) {
$data[] = [
'import_field_slug' => $mapping['value'],
'internal_field_slug' => $mapping['text'],
'custom_field' => $mapping['custom'],
'import' => 1,
'date_upd' => $now,
];
}
$update_feed_mappings = DB::table($db_name . '.feed_mappings')
->where('id_project', $token)
->where('id_feed', $id_feed)
->update($data);
But I got this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: update `shibbir_DB1`.`feed_mappings` set `0` = {\"import_field_slug\":\"date\",..........
Would you tell me how can I fix it?
update only works for a single row and each key must correspond to a column in your sql table. You can't use if with a multi-dimensional array.
You should move your update inside your loop to fix the issue.
foreach ($projectFieldOptions as $mapping) {
$data = [
'import_field_slug' => $mapping['value'],
'internal_field_slug' => $mapping['text'],
'custom_field' => $mapping['custom'],
'import' => 1,
'date_upd' => $now,
];
DB::table($db_name . '.feed_mappings')
->where('id_project', $token)
->where('id_feed', $id_feed)
->update($data);
}
Consider the code below please
$data = [];
$projectFieldOptions =
$data[] = [
'import_field_slug' => 1,
'internal_field_slug' => 1,
'custom_field' => 1,
'import' => 1,
'date_upd' => 1,
];
$data[] = [
'import_field_slug' => 2,
'internal_field_slug' => 2,
'custom_field' => 2,
'import' => 2,
'date_upd' => 2,
];
var_dump($data);
The output will be
array(2) {
[0]=>
array(5) {
["import_field_slug"]=>
int(1)
["internal_field_slug"]=>
int(1)
["custom_field"]=>
int(1)
["import"]=>
int(1)
["date_upd"]=>
int(1)
}
[1]=>
array(5) {
["import_field_slug"]=>
int(2)
["internal_field_slug"]=>
int(2)
["custom_field"]=>
int(2)
["import"]=>
int(2)
["date_upd"]=>
int(2)
}
}
So your update translates into something like that
update(['0' => array(...))
But update method needs something like that
update(['import_field_slug' => 1,...])
Conclusion: please update each record one by one inside your loop
Further reading
I am scratching my head to figure out why this legacy code supposedly will reset the indexes on a database table. Can you shed some light on it?
$employee = new Employee();
$employee->update([
'recruited' => 0,
'job_id' => null,
'job_start_date' => null,
'job_end_date' => null,
'interviewed' => 0
]);
There are a corresponding Eloquent model called Employee.
try to use :
DB::table('employees')->update([
'recruited' => 0,
'job_id' => null,
'job_start_date' => null,
'job_end_date' => null,
'interviewed' => 0
]);
I have a ManyToMany relationship setup but need to specify a value for the key in my array to attach.
$data = request()->validate([
'homework_title' => '', // string
'homework_description' => '', // string
'group_id' => '', // array
]);
$homework = request()->user()->homeworks()->create([
'homework_title' => $data['homework_title'],
'homework_description' => $data['homework_description'],
]);
$homework->groups()->attach($data['group_id'][key]);
group_id is an array and looks like the following:
[
{
"group_id": 1,
"group_name": "8x/En2"
},
{
"group_id": 2,
"group_name": "9x/En3"
}
]
How do I specify to attach only the group_id in array?
Got it to work, with:
Arr::pluck()
First time round I forgot to import the class (stupid me)!
use Illuminate\Support\Arr;
finally looking like the following:
$homework->groups()->attach(Arr::pluck($data['group_id'], 'group_id'));
I am making a web service in Laravel which is returning JSON.
I have created an Account model like so:
class Account extends Eloquent {
// The database table used by the model.
// (If not defined then lowercase and plural of class name is consider as a table name)
protected $table = "account";
// define which column can be mass assign
protected $fillable = array("user_id", "account_group_id", "generated_by", "image", "name",
"address", "zip", "area_id", "mobile", "email", "phone", "fax",
"website", "pan", "cst", "tin", "ecc", "iesc", "transport",
"other", "outstanding", "cform", "status", "mitp");
// To prevent column from mass assignment.
protected $guarded = array('id');
// Change Variable for CREATED_AT and UPDATED_AT
const CREATED_AT = 'itp';
const UPDATED_AT = 'utp';
}
I am fetching fields from Account using user_id and returning JSON via Response::json() in my controller
$accountData = Account::select('name', 'status', 'id', 'user_id', 'utp')->where('user_id', Auth::id())->first();
$return = array(
'result' => 'success',
'msg' => 'Login Successfully.',
'data' => $accountData
);
return Response::json($return);
In this, utp behaves as expected and returns a date as a string:
{
"result": "success",
"msg": "Login Successfully.",
"data": {
"name": "Demo",
"status": 0,
"id": 143,
"user_id": 207,
"utp": "2015-07-01 18:38:01"
}
}
However if I take each value separately from the account model like so:
$return = array(
'result' => 'success',
'msg' => 'Login Successfully.',
'data' => $accountData['user_id'],
'account_id' => $accountData['id'],
'utp' => $accountData['utp'],
'usertype' => 'account',
'status' => $accountData['status']
);
Then this gives some unexpected behavior from utp
{
"result": "success",
"msg": "Login Successfully.",
"data": 207,
"account_id": 143,
"utp": {
"date": "2015-07-01 18:38:01",
"timezone_type": 3,
"timezone": "Asia\\/Kolkata"
},
"usertype": "account",
"status": 0
}
Why does this happen with my timestamp field?
Because utp is a Carbon\Carbon instance. Model::toJson (actually Model::toArray, but both are used) handles that usually, and serializes a date to it's usual ISO3601-ish format
For expected behavior, you need to format the Carbon instance.
"utp" => $accountData['utp']->format("Y-m-d H:i:s"),
Alternatively, cast it to a string
"utp" => (string) $accountData['utp'],
I want to pass a result to a controller from a model after retrieving it from the DB depending on the user input. The values to be returned to the controller will be inserted to another table alongside other variables submitted through the same form. When i try running my code, it gives me the error below. Am using codeigniter 3.0.0
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: controllers/Service_providers.php
Line Number: 68
and this one too
Error Number: 1048
Column 'bs_name' cannot be null
INSERT INTO `merchants` (`bs_name`, `business_no`, `phone_no`, `location`, `licence_no`, `commission`, `balance`, `email`, `username`, `password`) VALUES (NULL, '4', '4', NULL, '4', '4', '4', 'muokid3#gmail.com', '4', 'e4da3b7fbbce2345d7772b0674a318d5')
Filename: C:\xampp\htdocs\mafya\system\database\DB_driver.php
Line Number: 330
here is my code:
Controller
function add()
{
$facility_code = $this->input->post('facilityno');
$data['fa_details'] = $this->Service_provider_model->getFacilityDetails($facility_code);
if ($fa_details = null)
{
echo "The Service Provider is not Recognized by the Government";
}
else
{
foreach ($data['fa_details'] as $detail)
{
$bs_name = $detail->facility_name;
$location = $detail->district;
}
$s_provider = array('bs_name' => $bs_name,
'business_no' => $this->input->post('businessno'),
'phone_no' => $this->input->post('phoneno'),
'location' => $location,
'licence_no' => $this->input->post('licenseno'),
'commission' => $this->input->post('commission'),
'balance' => $this->input->post('balance'),
'email' => $this->input->post('email'),
'username' => $this->input->post('username'),
'password' => md5($this->input->post('password')));
if ($this->Service_provider_model->save($s_provider))
{
echo "Service Provider Successfully Added";
}
else
{
echo "Service Provider NOT Added";
}
}
}
model:
function getFacilityDetails($facility_code)
{
$facility_details = 'facility_details';
$this->db->where('facility_code', $facility_code);
return $this->db->get($this->$facility_details);
}
function save($s_provider){
$this->db->insert($this->merchants, $s_provider);
return $this->db->insert_id();
}
You have to use result_array() or result() function to get value from db so you have change your model like
function getFacilityDetails($facility_code)
{
$facility_details = 'facility_details';
$this->db->where('facility_code', $facility_code);
return $this->db->get($this->$facility_details)->result();
}
Study about CI 3.0 from link.There are several new feature added.
For this query bs_name cannot be null so give some value with inverted comma or assign some default value in your table,You dont need to put null after that it will automatically take the default value.
INSERT INTO `merchants` (`bs_name`, `business_no`, `phone_no`, `location`, `licence_no`, `commission`, `balance`, `email`, `username`, `password`) VALUES (NULL, '4', '4', NULL, '4', '4', '4', 'muokid3#gmail.com', '4', 'e4da3b7fbbce2345d7772b0674a318d5').
Remove bs_name from query.it will be automatically filled by default value.
For another problem.please make sure your controller name starts with capital letter
eg. Example.php
This is new in CI 3.0.