laravel 4 insert one to one relationship example - insert

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!

Related

How to delete record with composite primary keys using Eloquent?

I'm trying to delete a record with two primary keys, using Eloquent - Laravel.
This is my model
class Like extends Model
{
//protected $primaryKey = ['crdid', 'usrid'];
public $timestamps = false;
use HasFactory;
}
Controller
try{
$dellike = Like::where('crdid', '=', $like->crdid, 'and')
->where('usrid', '=', $like->usrid)->first();
$dellike->delete();
}
catch(Exception $e){
return $e->getMessage();
}
Table definition
Schema::create('likes', function (Blueprint $table) {
$table->biginteger('crdid');
$table->biginteger('usrid');
$keys = array('crdid', 'usrid');
$table->primary($keys);
});
However, it gives me the below error;
Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: delete from `likes` where `id` is null)
I believe the 'id' is the default primary key used by Eloquent, but I'm not using it.
How should I define that, I'm not using the default primary key? or what is the correct way to delete the record with composite primary keys? Any help would be highly appreciated.
As Laravel Eloquent Docs says:
Eloquent requires each model to have at least one uniquely identifying "ID" that can serve as its primary key. "Composite" primary keys are not supported by Eloquent models. However, you are free to add additional multi-column, unique indexes to your database tables in addition to the table's uniquely identifying primary key.
So you can't use some methods of eloquent.
But seeing your code, looks like you are trying to create a model for a relationship pivot table (many to many between user and crd (what is crd?! no reason to abreviatte here.)
Try defining a many to many relationship on your user and crd model.
Also laravel naming convention for key columns is: model_name_id for a model named ModelName
But, just to delete, you can skip the first in your query:
Like::where('crdid', '=', $like->crdid, 'and')
->where('usrid', '=', $like->usrid)->delete();
This happens because when you delete a model (your attempt) laravel uses the primary key field (defaults to id) as where condition. But manually querying, you are defining the where clauses of the delete.
Just create additionnal column named id in the table as unique with auto-increment option. Eloquent will use it to delete each row with delete function.
Example with Laravel 5.5 :
$logement = Logement::findOrFail($id);
$commodites = Commodites_logement::all()->where('logement_id','=',$logement->id);
foreach ($commodites as $commodite) {
$commodite->delete();
}

Why am I getting the error in post? Laravel

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.

Illuminate \ Database \ QueryException (42000) SQLSTATE[42000]: Syntax error or access violation

trying to execute the following query on the FriendController
$friends = Auth::User()->friends;
and that is the friends function on the User model
public function friends()
{
return $this->belongsToMany('App\Friend', 'friends', 'user_id', 'friend_id');
}
but on hitting the route i get the following error
Illuminate \ Database \ QueryException (42000)
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'friends' (SQL: select friends.*, friends.user_id as pivot_user_id, friends.friend_id as pivot_friend_id from friends inner join friends on friends.id = friends.friend_id where friends.user_id = 2)
Pivot tables should almost never have a model. If you're trying to use friends as a pivot table for two users, then the relationship should be referencing App\User, not App\Friend (or static which represents the current class).
public function friends()
{
return $this->belongsToMany(static::class, 'friends', 'user_id', 'friend_id');
}
You'd want to return a collection of users, not "friends" since friend isn't an entity, it's a relationship.

Laravel - Many to Many Polymorphic Relation with Extra Fields

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

Laravel3: Eloquent/Fluent fails during UPDATE statement

$account = Account::where('account_id', '=', $account_id)->first();
$account->username = 'New_Username';
$account->password = 'Password';
$account->save();
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'
Why is this happening?
When you update an Eloquent model it will use the model's primary key. The default primary key is id, you can change this by adding the following in your class:
public static $key = 'account_id';
Be warned that there are some hard-coded references to id in Laravel, so the best advise is still to use id as a primary key when designing your databases for Eloquent.
Reference: laravel/database/eloquent/model.php

Resources