php - Laravel Eloquent - 多对一关系

标签 php mysql laravel-5 eloquent

我有模型: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);
    }
}

Controller :

ArtObject Controller :

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

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

最佳答案

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

像这里一样,一个 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();


 }

这样做之后,您可以通过您在Photo模型中定义的方法来获取照片的相关ArtObject,将ArtObject和Photo表关联在一起。您也可以通过ArtObject中定义的方法来获取与ArtObject相关的照片。

在 ArtObject 模型中:-

 public function photos()
{
    return $this->hasMany('App\Photo');
}

在照片模型中:-

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

关于php - Laravel Eloquent - 多对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43752025/

相关文章:

php - 使用 MySql Update 和 PHP 制作表情符号

php - Laravel 5.8 - 如何排序(orderBy)多重关系

Php Mysql SELECT 查询 1 列等于 1 个变量

mysql - 每周最大平均收视率

java - 如何在executeQuery方法中编写sql查询?

php - 我如何在 Laravel 5.2 查询中返回自定义文本?

Laravel 5.6 Api - 搜索、排序和过滤数据列表

php - 登录网站 cURL

php - 将 match_all 与过滤器一起使用

php - codeIgniter 3.0 中的 Curl 类