abr
abr

Reputation: 2129

Laravel inserting by relationship to composite key table

I have these tables currently:

User table

id (primary key), name, email

User Model

protected $fillable = ['name', 'email'];
protected $visible = ['id','name','email'];
//Relationship
public function customAttributes()
{
    return $this->hasMany('App\Models\UserAttribute');
}

UserAttribute Table

user_id, attribute_id, value //user_id and attribute_id is a composite key, both foreignkeys acting as primary keys establishing an unique combination

UserAttribute Model

protected $fillable = ['user_id', 'attribute_id','value'];
protected $visible = ['user_id', 'attribute_id','value'];

I'll use the following example to explain the issue:

$user = $this->user->create(['name' => 'admin', 'email' => '[email protected]']);
//This works
$user->customAttributes()->save(new \App\Models\UserAttribute(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1']));
//This does not work 
$user->customAttributes()->create([new \App\Models\UserAttribute(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1'])]);

I could just repeat the save for every custom that I want since it works, but I'm trying to figure out why create doesn't work.

The error I'm getting when I use create is (and yes, I've checked the record exists in the table that isn't listed here):

Cannot add or update a child row: a foreign key constraint fails (`testdatabase`.`user_attributes`, 
CONSTRAINT `user_attributes_attribute_id_foreign` FOREIGN KEY (`attribute_id`) REFERENCES `attributes` (`id`))

This is the query it's trying to execute:

insert into `user_attributes` (`user_id`) values (1)

I'm just curious at why this doesn't work with create, I'm not sure if it's something related to this specific scenario (create to a composite key table by relationship). It's somewhat ignoring the value and attribute_id field in the query that is executing

Upvotes: 0

Views: 921

Answers (2)

Teoman Tıngır
Teoman Tıngır

Reputation: 2901

customAttributes() already returns you instance of UserAttribute model, you don't need to enject that dependency when you use create() method via that relation

your query should be like below;

$user->customAttributes()->insert([
   [
   'user_id' => $user->id,
   'attribute_id' => 1,
   'value' => 'Just a custom1'
   ],
   [
   'user_id' => $user->id,
   'attribute_id' => 2,
   'value' => 'Just a custom2'
   ],
]);

Upvotes: 1

Jinal Somaiya
Jinal Somaiya

Reputation: 1971

try this:

$user->customAttributes()->create(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1']);

Upvotes: 1

Related Questions