我是Laravel的新手。我正在开发laravel 5应用程序,并且卡在这里。我有2个这样的模型:
class Message extends Eloquent{ public function user() { return $this->belongsTo('App\User', 'from'); } public function users() { return $this->belongsToMany('App\User')->withPivot('status'); } } class User extends Eloquent { public function messages() { return $this->hasMany('App\Message', 'from'); } public function receive_messages() { return $this->belongsToMany('App\Message')->withPivot('status'); } }
消息和用户之间存在多对多关系,因此给我一个数据透视表:
Table Name: message_user Colums: message_id user_id status
我有这样的SQL查询:
update message_user set status = 1 where user_id = 4 and message_id in (select id from messages where message_id = 123)
如何将此查询转换为laravel对等词?
下面的代码解决了我的问题:
$messages = Message::where('message_id', $id)->get(); foreach($messages as $message) $message->users()->updateExistingPivot($user, array('status' => 1), false);