Laravel Eloquent - 多对一关系

sri*_*igu 3 php mysql eloquent laravel-5

我有模型:ArtObjects 和照片:

class Photo extends Model
{
    protected $fillable = ['caption','description','alternative_text'];

    public function artObject()
    {
        return $this->belongsTo('App\ArtObject');
    }
}

class ArtObject extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'description',
        'rating',
        'popularity',
        'type',
        'price'
    ];

    public function photos()
    {
        return $this->hasMany(ArtObjectPhoto::class);
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

艺术对象控制器:

public function store(ArtObjectUploadRequest $request)
{
    $art_object = ArtObject::create(request(['title', 'description', 'rating', 'popularity', 'type', 'price']));

    $this->validate($request, [
        'title' => 'required',
        'description' => 'required'
    ]);

    foreach ($photo_ids = Input::get('photos') as $photo_id) {

        $photo = Photo::find($photo_id);

        /*
        Problem is here - The user wants to attach the selected photos with
        the art-object, ........ Please advise, thanks in anticipation !!!
        */  

    }

    //save the artobject to the database
    $art_object->save();

    //And redirect to the home page
    return redirect('/');
}
Run Code Online (Sandbox Code Playgroud)

问题:用户想要将选定的照片与艺术品附加在一起。请注意,照片已存在于数据库中。我尝试过选项 - save()、associate () 但没有任何帮助。我的理解是,一旦我找到 () 照片,它应该给我照片对象,我应该能够使用 $art_object 保存 () 。它希望我 new() 并从数据库分配并分配给照片对象。但我认为这不是正确的做法。我相信这不是实现多对关系的最佳方式,那么保存这种关系的最佳方式是什么。请指教,期待中,谢谢!!!

小智 5

根据数据库中的多对一关系规则,连接表的外键总是保存在具有“多”关系的表中。

就像这里一样,一个 ArtObject 可以有很多照片。所以,那个“许多”表就是照片。您的照片模型必须有一个名为 art_object_id 的属性作为外键。

然后,您必须首先保存该 ArtObject 对象,并将该对象的 id 保存在 photos 表中用户选择 id 的所有行中。

$art_object = ArtObject::create(request(['title', 'description', 'rating', 'popularity', 'type', 'price']));

$this->validate($request, [
    'title' => 'required',
    'description' => 'required'
]);

 //save the artobject to the database
$art_object->save();

foreach ($photo_ids = Input::get('photos') as $photo_id) {

    $photo = Photo::find($photo_id);
    $photo->art_object_id = $art_object->id;
    $photo->save();


 }
Run Code Online (Sandbox Code Playgroud)

完成此操作后,您可以通过在 Photo 模型中定义的方法来获取照片的相关 ArtObject,将 ArtObject 和 Photo 表关联在一起。您还可以通过在 ArtObject 中定义的方法来获取与 ArtObject 相关的照片。

在 ArtObject 模型中:-

 public function photos()
{
    return $this->hasMany('App\Photo');
}
Run Code Online (Sandbox Code Playgroud)

在照片模型中:-

 public function artObject()
{
    return $this->belongsTo('App\ArtObject');
}
Run Code Online (Sandbox Code Playgroud)