If I have a many-to-many relationship it\'s super easy to update the relationship with its sync
method.
But what would I use to synchronize a one-to-many re
Another manual sync process :
Add Model
class Post extends Model
{
protected $fillable = ["name"];
function links()
{
return $this->hasMany("App\Link");
}
}
class Link extends Model
{
protected $fillable = ["name", "post_id"];
function post()
{
return $this->belongsTo("App\Post");
}
}
class PostLink extends Model
{
protected $fillable = ["post_id", "link_id"];
function post()
{
return $this->belongsTo("App\Post");
}
function link()
{
return $this->belongsTo("App\Link");
}
}
Here we go
// list ids from request
$linkIds = $request->input("link");
if (!empty($linkIds))
{
// delete removed id from list in database
PostLink::where('post_id','=', $post->id)->whereNotIn('post_id', $linkIds)->delete();
// list remain id in database
$postLinkIds = $post->links()->pluck('post_id')->toArray();
// remove ids that already on db
$linkIds = array_diff($linkIds, $postLinkIds);
// check if still have id that must be save
if (!empty($linkIds))
{
foreach ($linkIds as $id)
{
// save id to post
$post->links()->create(['post_id' => $id]);
}
}
}