How to update a pivot table using Eloquent in lara

2019-01-26 05:46发布

问题:

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('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');
    }
}

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

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)

How can I translate this query to the laravel equivalent?

回答1:

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);


回答2:

You may use one of these two functions, sync() attach() and the difference in a nutshell is that Sync will get array as its first argument and sync it with pivot table (remove and add the passed keys in your array) which means if you got 3,2,1 as valued within your junction table, and passed sync with values of, 3,4,2, sync automatically will remove value 1 and add the value 4 for you. where Attach will take single ID value

The GIST: if you want to add extra values to your junction table, pass it as the second argument to sync() like so:

$message = Messages::find(123);
$user = User::find(4);

// using ->attach for single message
$user->message()->attach($message->id,['status' => 1 ]);



// using ->sync for multiple messages
$message2 = Messages::find(456); // for testing
$user->message()->sync([$message->id => ['status' => 1 ],$message2->id => ['status' => 1 ] ]);


回答3:

For Updating your pivot table you can use updateExistingPivot method.