Laravel : 多态关系 + 访问器
Laravel : Polymorphic Relations + Accessor
我有一个使用多态关系的 Gallery
table,所以我可以将 Images
和 Videos
添加到我的画廊列表中。
在 Gallery
table 中,我有一个 galleryable_type
列,其中填充了 App\Video
或 App\Image
。
有没有办法让我使用访问器(文档 here)将 galleryable_type
的值更改为 video
或 image
以便我可以使用JS 中的那一列决定我正在处理的画廊项目类型?
我尝试了以下方法:
/**
* Get and convert the makeable type.
*
* @param string $value
* @return string
*/
public function getMakeableTypeAttribute($value)
{
return str_replace('app\', '', strtolower($value));
}
但我最终遇到以下错误:
FatalErrorException in Model.php line 838:
Class '' not found
我假设这与在多态关系之前处理访问器有关,但我不确定。
我可以简单地在我的控制器中使用以下内容:
foreach (Gallery::with('galleryable')->get() as &$gallery) {
$gallery->galleryable_type = str_replace('app\', '', strtolower($gallery->galleryable_type ));
}
但这似乎是一种狡猾的做事方式。 Laravel 大师能否阐明解决此问题的最佳方法?
谢谢!
好吧,我找到了解决这个问题的有趣方法。
在您的模型(App\Video
和 App\Image
)中,您必须添加:
protected $morphClass = 'video'; // 'image' for image class
然后在服务提供商 class 中的 register
方法中添加:
$aliasLoader = \Illuminate\Foundation\AliasLoader::getInstance();
$aliasLoader->alias('video', \App\Video::class);
$aliasLoader->alias('image', \App\Image::class);
这将导致您在数据库的 galleryable_type
中写入 image
和 video
而不是 class 名称。
现在您可以通过以下方式轻松获得此值:
echo $model->galleryable_type;
我有一个使用多态关系的 Gallery
table,所以我可以将 Images
和 Videos
添加到我的画廊列表中。
在 Gallery
table 中,我有一个 galleryable_type
列,其中填充了 App\Video
或 App\Image
。
有没有办法让我使用访问器(文档 here)将 galleryable_type
的值更改为 video
或 image
以便我可以使用JS 中的那一列决定我正在处理的画廊项目类型?
我尝试了以下方法:
/**
* Get and convert the makeable type.
*
* @param string $value
* @return string
*/
public function getMakeableTypeAttribute($value)
{
return str_replace('app\', '', strtolower($value));
}
但我最终遇到以下错误:
FatalErrorException in Model.php line 838:
Class '' not found
我假设这与在多态关系之前处理访问器有关,但我不确定。
我可以简单地在我的控制器中使用以下内容:
foreach (Gallery::with('galleryable')->get() as &$gallery) {
$gallery->galleryable_type = str_replace('app\', '', strtolower($gallery->galleryable_type ));
}
但这似乎是一种狡猾的做事方式。 Laravel 大师能否阐明解决此问题的最佳方法?
谢谢!
好吧,我找到了解决这个问题的有趣方法。
在您的模型(App\Video
和 App\Image
)中,您必须添加:
protected $morphClass = 'video'; // 'image' for image class
然后在服务提供商 class 中的 register
方法中添加:
$aliasLoader = \Illuminate\Foundation\AliasLoader::getInstance();
$aliasLoader->alias('video', \App\Video::class);
$aliasLoader->alias('image', \App\Image::class);
这将导致您在数据库的 galleryable_type
中写入 image
和 video
而不是 class 名称。
现在您可以通过以下方式轻松获得此值:
echo $model->galleryable_type;