Reputation: 2166
I have a Post model:
class Post extends Model
{
protected $fillable = [
'title',
'user_id',
'token',
'body'
];
public function favorites()
{
return $this->hasMany(Favorite::class);
}
public function addFavorite($state = 1)
{
$this->favorites()->create(compact('state'));
}
}
Favorite model:
class Favorite extends Model
{
protected $fillable = ['user_id', 'post_id', 'state'];
}
When I test in tinker:
$post = Post::first();
$post->addFavorite();
It returns me an error below:
Illuminate/Database/QueryException with message 'SQLSTATE[HYOOO]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into favorites...
Why it ask user_id
when it is given in the post? Question is do I necessarily need to input the user_id
to achieve this?
Upvotes: 0
Views: 34
Reputation: 3397
The question of whether user_id
is necessary is up to you. Will it come in handy later on? Does having it on the posts table suffice?
It is asking for user_id
because you do not have a default value field on that field in the favorites table. You can either set a default value, remove it from the table (if you decide you don't need it), OR provide it when creating via the relationship:
class Post extends Model
{
protected $fillable = [
'title',
'user_id',
'token',
'body'
];
public function addFavorite($state = 1)
{
$this->favorites()->create([
'state' => $state,
'user_id' => $this->user_id,
]);
}
public function removeFavorite()
{
$this->addFavorite(0);
}
}
Don't forget to include the relationship definition of favorites
on the Post model.
Based on the plural name, it seems that a post has many favorites, but then your removeFavorite() method calls the addFavorite method?? This would not actually remove anything - it would create a new record.
Upvotes: 2
Reputation: 3527
Since Favorite
model is related to Post
model and you create it via relation()->create()
, you can skip specifying post_id
as Laravel can deduce it. But you do have to specify user_id
, because there's no way for your code to know that favourite.user_id
and post.user_id
is the same. So in short: yes, you have to specify user_id.
Upvotes: 2