如何在 Laravel 5 中使用 Eloquent 更新数据透视表
我是 Laravel 的新手.我正在开发一个 Laravel 5 应用程序,但我被困在这里.我有 2 个这样的模型:
I am new to laravel. I am working on a laravel 5 app and I am stuck here. I have 2 models as such:
class Message extends Eloquent{
public function user()
{
return $this->belongsTo('AppUser', 'from');
}
public function users()
{
return $this->belongsToMany('AppUser')->withPivot('status');
}
}
class User extends Eloquent {
public function messages()
{
return $this->hasMany('AppMessage', 'from');
}
public function receive_messages() {
return $this->belongsToMany('AppMessage')->withPivot('status');
}
}
Message 和 User 之间存在多对多关系,为我提供了一个数据透视表:
There exist a many-to-many relationship between Message and User giving me a pivot table as such:
Table Name: message_user
Colums:
message_id
user_id
status
我有一个这样的 SQL 查询:
I have an SQL query as such:
update message_user
set status = 1
where user_id = 4 and message_id in (select id from messages where message_id = 123)
如何将此查询转换为 Laravel 等效项?
How can I translate this query to the laravel equivalent?
推荐答案
下面的代码解决了我的问题:
The code below solved my problem:
$messages = Message::where('message_id', $id)->get();
foreach($messages as $message)
$message->users()->updateExistingPivot($user, array('status' => 1), false);
相关文章