如何在 ELoquent 中以一对多关系附加项目?

How to attach item in one-to-many relation in ELoquent?

我的模型 Post 可能有很多文件。有关文件的信息存储在模型 File 的数据库中。所以每个Post可以有很多File,但是每个File只有一个Post.

class Post extends Eloquent {

    protected $table    = 'posts';
    protected $guarded  = array('id');

    public function files()
    {
        return $this->hasMany('File', 'post_id', 'id');
    }
}

class File extends Eloquent {

    protected $table = 'files';

    public function post()
    {
        return $this->belongsTo('Post', 'post_id');
    }
}

问题是文件是在 post 保存之前上传的。当我保存 post 时,我有一个文件 ID 数组,如 array(34, 35, 36);。如何将它们与当前 post 联系起来? attachsync 方法目前只适用于 many-to-many 关系。

嗯,有 save() / saveMany(),但那些希望 Eloquent 模型通过。不过,您可以做的是手动更新它:

$post = new Post;
// ....
$post->save();
File::whereIn('id', [34, 35, 36])->update(['post_id' => $post->id]);

或者如果您想使用关系方法:

$files = File::whereIn('id', [34, 35, 36])->get();
$post->files()->saveMany($files);