如何编写两个相关模型之间的关系并利用该关系赋值?

问题描述 投票:0回答:1

所以我目前正在努力解决我的

AlbumController
store
功能,我需要在我的
albums
表中存储一个相册,包括选择要包含在相册中的图片的索引,其中然后,包含的图片将在另一个存储名为
album_id
的图片的表中使用外键
photos
进行索引。我需要为所有选定的图片分配新创建的相册的值,这是我的
album_id
表上的主键
albums
,但我仍然没有弄清楚如何使用 Eloquent 关系来分配值。

这是我的

store
控制器内的
AlbumController
功能:

/**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $user_id = Auth::id();
        $data = [
            'album_name' => $request->get('album_name'),
            'album_description' => $request->get('album_description'),
            'user_id' => $user_id // I still hasnt figured out how assign the user_id value to the album using Eloquent ORM relationships either
        ];
        //album::create($data); // creates the album
        $photos = ['photos' => $request->get('photo_checkbox')]; // insert photos checklisted in the create album form
        foreach ($photos as $photo){
            $album_query =  Photo::where('photo_id',$photo); // assign the photos checklisted album_id according to the album just created
            $result = $album_query->albums()->save(); // tried to use Laravel's Eloquent ORM relationships
            /** $album = Album::where('album_name',$data['album_name']); 
             * $result = $album_query->update(['album_id' => $album->album_id]); // alternative without Eloquent ORM relationships
             */
        }
        dd($result);
        session()->now('data','album_name');
        return redirect(route('album.album'))->with('success','album "'.$data['album_name'].' '.'" has been registered.');
    }

我将我的相册定义为

Album
模型的实例,其中可以包含许多照片:

class Album extends Model
{
    use HasFactory;
    protected $table = "albums";
    protected $primaryKey = "album_id";
    const CREATED_AT = 'data_created';
    const UPDATED_AT = 'data_modified';

    protected $fillable = [
        'album_name',
        'album_description',
        'user_id'
    ];

    public function photos() : HasMany {
        return $this->hasMany(Photo::class,'album_id','album_id');
    }
    public function users() : BelongsTo {
        return $this->belongsTo(GalleryUser::class,'user_id','gallery_user_id');
    }
}

虽然我的照片是

Photo
模型的实例:

class Photo extends Model
{
    /** @use HasFactory<\Database\Factories\PhotoGalleryFactory> */
    use HasFactory;
    protected $table = "photos";
    protected $primaryKey = "photo_id";
    const CREATED_AT = 'data_created';
    const UPDATED_AT = 'data_modified';

    protected $fillable = [
        'photo_title',
        'photo_description',
        'photo_location',
        'user_id',
        'album_id'
    ];
    public function comments() : HasMany {
        return $this->hasMany(PhotoComment::class,'comment_id','comment_id');
    }
    public function albums() : BelongsTo {
        return $this->belongsTo(Album::class,'album_id','album_id');
    }
    public function users() : BelongsTo {
        return $this->belongsTo(GalleryUser::class,'user_id','gallery_user_id');
    }
}

在我的

store
控制器的
AlbumController
函数的这个片段中,我编写了两个不同的选项来将值分配给外键
album_id
,一个具有雄辩的关系,一个没有:

...
foreach ($photos as $photo){
            $album_query =  Photo::where('photo_id',$photo); // assign the photos checklisted album_id according to the album just created
            $result = $album_query->albums()->save(); // tried to use Laravel's Eloquent ORM relationships
            /** $album = Album::where('album_name',$data['album_name']); 
             * $result = $album_query->update(['album_id' => $album->album_id]); // alternative without Eloquent ORM relationships
             */
        }
...

但是当我尝试做

$album_query->albums()->save()
时,我却得到了
Call to undefined method Illuminate\Database\Eloquent\Builder::albums()
。我尝试将
->get()
添加到
$album_query
,但我得到了
 Method Illuminate\Database\Eloquent\Collection::albums does not exist.
。由此,我觉得我可能以错误的方式编写了关系,并且如果我能弄清楚我的
Album
模型和我的
Photo
模型之间的关系,那么代码可以工作。

同时,替代方案看起来也不是很好,尽管我认为它是一个足够合理的代码,但我觉得雄辩的 ORM 并没有被广泛使用,如果是这样的话,我最好不要使用它。

php laravel eloquent
1个回答
0
投票

您可以简单地使用

associate
方法来关联照片:

$user = Auth::user();

$album = $user->albums()->create([
    'album_name' => $request->get('album_name'),
    'album_description' => $request->get('album_description'),
]);

....

foreach ($photos as $photo) {
   $photo->album()->associate($album);
   $photo->save();
}
© www.soinside.com 2019 - 2024. All rights reserved.