likes table migration code
$table->primary(['user_id', 'post_id']);
$table->foreignId('user_id');
$table->foreignId('post_id');
$table->boolean('liked');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('post_id')
->references('id')
->on('posts')
->onDelete('cascade');
$table->unique(['user_id', 'post_id']);
likes post eloquent relationship
public function likes()
{
return $this->hasMany(Like::class);
}
like function code
public function like($user = null, $liked = true)
{
$this->likes()->updateOrCreate(
[
'user_id' => $user ? $user->id : auth()->id(),
],
[
'liked' => $liked
]
);
}
when i var_dump updateOrCreate i get:
App\Models\Like {#1248 ▼
#guarded: []
#connection: "mysql"
#table: "likes"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: true
#attributes: array:6 [▼
"user_id" => 1
"post_id" => 11
"liked" => true
"updated_at" => "2021-07-17 00:16:15"
"created_at" => "2021-07-17 00:16:15"
"id" => 0
]
#original: array:6 [▼
"user_id" => 1
"post_id" => 11
"liked" => true
"updated_at" => "2021-07-17 00:16:15"
"created_at" => "2021-07-17 00:16:15"
"id" => 0
]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
}
as you can see there is an id element, i don't know where that came from.
nb.
- when i run the like function first time, it runs correctly (it adds the record to the table)
- when i run it again it fails and it gives me this mysql error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update likes set liked = 1, likes.updated_at = 2021-07-17 00:20:29 where id is null)
edit:
- when i add manually an id element to likes table, it works.