Framework: [Proposal] sync and attach on HasMany

Created on 15 Jan 2014  路  5Comments  路  Source: laravel/framework

Not much to add than the title itself. Any reason this can't/shouldn't be implemented?

class User extends Illuminate\Database\Eloquent\Model
{
    public function blog()
    {
        return $this->belongsTo('Blog', 'blog_author_id');
    }
}

class Blog extends Illuminate\Database\Eloquent\Model
{
    public function authors()
    {
        return $this->hasMany('User', 'blog_author_id');
    }
}

$blog = Blog::find(5);
// blog #5's authors are users with id 1, 2 and 3
$blog->authors()->sync([1,2,3]);
// add user #4 to that list
$blog->authors()->attach(4);

Most helpful comment

I have a Product with a hasMany productOptions. When I update the form, some productOptions are added, some updated, some removed, and some left alone. This would be nice to have.

All 5 comments

I don't get it, before you called sync and attach who did those authors belong to?

They could belong to no blog, the same blog or another blog - sync would remove all existing authors and attach the ones provided. Attach would just attach a new one. Both would overwrite the current BelongsTo relationship the User has to Blog. A more detailed code sample...

$blog = Blog::find(5);

// set blog #5's authors to users 1, 2 and 3
$blog->authors()->sync([1,2,3]);

// add user #4 to that list
$blog->authors()->attach(4);

$otherBlog = Blog::find(4);

// user #3 is removed from his previous blog and attached to this one
// 5 and 6 are added as before
$otherBlog->authors()->sync([3,5,6]);

// user #1 is removed from his previous blog and attached to this one
$otherBlog->authors()->attach(1);

An idea might be to make sync/attach not overwrite existing relationships on the related model(s), but have forceSync/forceAttach methods that do overwrite.

I have a Product with a hasMany productOptions. When I update the form, some productOptions are added, some updated, some removed, and some left alone. This would be nice to have.

Honestly I don't find this very intuitive. Are the disconnected authors set to blog_id "null" or something? I dunno... not comfortable with this.

I have a similar situation. I'm trying to saving "Trips". Each "Trip" has a number of "Stops". The Booking and its Stops are all editable from the same form. Right now I save them like this:

foreach($_POST['stop'] as $stopData) {
    $stopId = array_get($stopData,'id');
    if($stopId) {
        $stop = BookingStop::findOrFail($stopId);
        $stop->fill($stopData);
    } else {
        $stop = new BookingStop($bookingData);
    }
    $stop->trip()->associate($trip);
    $stop->save();
}

If, however, the user removes a Stop from the Trip then I need that Stop to be deleted from the database entirely. Right now I don't have a way to do that; I will need to collect up all the Stop IDs and then manually run a delete where not in (<stop ids>).

Was this page helpful?
0 / 5 - 0 ratings