[英]How to update a row in DB without overwriting the existing data with laravel 5.2
我有一個表,用於存儲用戶感興趣的主題以及用戶ID和主題ID。 桌子看起來像
Topic name topic id User-id
Sports 1 1
Education 2 3
Family 3 1
我要做的是,當一個新用戶(用戶ID為“ 3”)將他的興趣添加為主題體育活動時,那么第一行應如下所示
Topic name topic id User-id
Sports 1 1,3
當我嘗試更新時,它會覆蓋整個列,例如
Topic name topic id User-id
Sports 1 3
什么是正確的做法?
正確的方法是使用Many-To-Many
關系:
表格:
users (id, ....);
topics (id, ....);
topic_user (topic_id, user_id);
PHP:
class User extends Model {
public function topics() {
return $this->belongsToMany('App\Topic');
}
}
和:
class Topic extends Model {
public function users() {
return $this->belongsToMany('App\User');
}
}
有關更多詳細信息,請參閱https://laravel.com/docs/5.2/eloquent-relationships 。
我希望這將有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.