So I'm trying to create a simple REST API using Laravel.
While testing out the API with creating new items to the database I'm receiving an error:
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (world.cities, CONSTRAINT cities_ibfk_1 FOREIGN KEY (CountryCode) REFERENCES country (Code)) (SQL: insert into cities (Name, CountryCode, District, Population, updated_at, created_at) values (Valhalla, vlh, Ragnar Alley, 200000000, 2020-02-19 01:07:26, 2020-02-19 01:07:26)) in file C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 669
here's the Controller:
public function createCity(Request $request) {
$city = new City;
$city->Name = $request->Name;
$city->CountryCode = $request->CountryCode;
$city->District = $request->District;
$city->Population = $request->Population;
$city->save();
Model:
class City extends Model
{
protected $table = 'cities';
protected $fillable = ['Name', 'CountryCode', 'District', 'Population'];
}
Help would be appreciated as I can't figure out why I'm getting the error after POST.
Thanks in advance.
You try to add vlh as contry_code value into your model .but this field refrence to another model that have country name and in that table there is not any record with this condition and vlh value is unknown or it.
You can romve relation between these models (if it is possible) or first find the id of country that has that code and then insert it into your model.
Related
I want to fetch the data from profile table using a child table of other parent table.
Here is the tables
Profile table
id
profile_name
Transaction table
id
transaction_name
Sub transaction table
id
transaction_id
profile_id
Now i want to get the profile name from transaction model using eager loading . i tried has one Though relationship in transaction model but returning null
Here is my relationship in Transaction model
public function profileName()
{
return $this->hasOneThrough(
Profiler::class,
SubTransaction::class,
'profile_id',
'id',
'id',
'transaction_id',
);
}
Here is where i am trying to fetch from transaction controller
$options = Transaction::with([
'profileName:id,profile_name as profileName',
])
->get();
It returns null because I think you have a little problem about matching between foreign keys and local keys. You could try the following code:
return $this->hasOneThrough(
Profiler::class, //Final model we wish to access
SubTransaction::class, //The name of the intermediate model
'transaction_id', //Foreign key on sub_transaction table
'id', //Foreign key on profile table
'id', //Local key on transaction table
'profile_id', //Local key on sub_transaction table
);
If you have any problem, tell me.
I've set a custom primary key in my Task.php model.
class Task extends Model
{
//
protected $primaryKey = 'taskn';
public $incrementing = false;
}
I've also set taskn as my primary key in the migration:
$table->string('taskn');
$table->primary('taskn');
But I still get the error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `Task` where `id` = 1 limit 1)
For some reason Laravel still tries to query id.
I am trying to retrieve the data with the following call:
$tasks = DB::table('tasks')->find($taskn);
What is wrong here?
I'm doing $tasks = DB::table('tasks')->find($taskn);
Here's your problem.
DB:: calls don't use Eloquent - you're completely bypassing it. If you do Task::find($taskn) it'll work, but DB:: calls have no idea about your $primaryKey settings.
I've just installed new laravel project. After that, I created new Model but when I use create() function, it just show me that my new rows has been duplicated.
This is my code:
protected $fillable = ['id', 'setting_name', 'expected_type', 'default_val', 'modified_val'];
// protected $guarded = ['created_at', 'updated_at'];
function test() {
$input = ['setting_name' => 'Test',
'expected_type' => '123',
'default_val'=>'123',
'modified_val'=>'123'];
// dd($input);
//both next two lines do not working
Setting::create($input);
return Setting::firstOrNew($input);
}
I checked the error :
"Integrity constraint violation: 1062 Duplicate entry '' for key 'setting_name' (SQL: insert into settings (updated_at, created_at) values (1474452834, 1474452834))"
What i did wrong ?
At the end of the day, I realized that I created __constructor for my model, that why I could not create object normally.
I removed that constructor and it works well. :D
The error says you're trying to insert row with setting_name which is already exists in a table and you have unique constraint for this column.
So, make sure you're inserting this row only once and there is no any other row with the same setting_name value.
How can I define a many to many polymorphic relation with extra fields?
I have three (or more, as it is a polymorphic relation) tables.
tags table: id, name
tagged table: id, tag_id, taggable_id, taggable_type, user_id
posts table: id, record, timestamps
users table: id, name, email
The user_id on the tagged table referes to the users table on column id.
In my Post model I have:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged');
}
and in my Tag model I have:
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable','tagged');
}
Then when I am try this in my controller:
$tag = new \App\Tag(
array(
'tag'=>"someTag"
));
$tag->save()
$post = \App\Post::find($id);
$post->tags()->save($tag);
I get Integrity Constraint Violation for not having a user_id:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (hb.tagged, CONSTRAINT tagged_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into tagged (tag_id, taggable_id, taggable_type) values (26, 2, App\Resource)).
Which is somewhat expected, as I have never had the chance to define or declare the user_id field.
Also, I have tried withPivot() on tags relation as follows, to no avail:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged')->withPivot('user_id');
}
Like in the comment: withPivot has nothing to do with saving/creating. If you want to pass additional pivot data when saving, do this:
$post->tags()->save($tag, ['user_id' => $userId]);
Ok so I can't seem to get a insert to work with a one to one relation ship. I will start with my models:
Class Maintenance{
public function taskList(){
return $this->hasOne('App\Models\TaskLists','maintenance_id','list_id');
}
Class TaskLists{
public function maintenance(){
return $this->belongsTo('App\Models\Maintenance','maintenance_id','list_id');
}
ok, and my controller:
$log = new Maintenance();
$log->status = $status;
$log->save();
$list = TaskLists::create(array('title'=>'Maintenance Log'));
$log->taskList()->save($list);
now here is the error I get:
Illuminate \ Database \ QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'maintenance_id' cannot be null (SQL: insert into `taskLists` (`title`, `maintenance_id`, `updated_at`, `created_at`) values (Maintenance Log, , 2014-06-18 18:00:50, 2014-06-18 18:00:50))
So laravel documentation doesn't really state this is the way to insert a one to one relationship. So my question is, how do I do that? Can you provide and example.
Thanks much!