【发布时间】:2018-08-29 02:06:40
【问题描述】:
在我的项目中,我正在处理我发现很难理解的多态关系。请记住,我是编程的初学者。我的数据库看起来像这样:
Themes
id - integer
composer_package - string
name - string
Plugins
id - integer
composer_package - string
name - string
Products
id - integer
name - string
...
productable_id - integer
productable_type - string
在下面的 store 方法中。我正在获取所选主题的 ID。然后我通过$theme = Product::find($selectedTheme); 找到该主题。 $selectedTheme 是主题的 ID。我有一个名为predefinedArray 的数组,其中包含theme 的所有可填充字段。然后它将特定主题的所有值放入一个名为 selected_theme 的会话中。
public function store(Request $request)
{
$selectedTheme = null;
foreach($request->input('theme') as $key => $value) {
if($value === 'selected') {
$selectedTheme = $key;
}
}
$theme = Product::find($selectedTheme);
foreach($this->predefinedArray as $value) {
$request->session()->put('chosen_theme.' . $value, $theme->$value);
}
$data = $request->session()->all();
return redirect('plugins');
}
主题是一个产品。我需要获取与之关联的 composer_package 并将其放入请求中。例如,我找到一个 ID 为 20 的主题,该主题的 productable_id 为 5。然后我需要在主题表中获取 ID 为 5 的 composer_package 并将其放入请求中。我怎样才能做到这一点?该数组当前如下所示:
如您所见,composer_package字段为空,需要填写与所选产品关联的composer_package。
我的模型如下所示:
产品
public function productable()
{
return $this->morphTo();
}
public function order_items()
{
return $this->hasMany(Orderitems::class);
}
主题
public function webshops()
{
return $this->hasMany(Webshop::class);
}
public function products()
{
return $this->morphMany(Product::class, 'productable');
}
我怎样才能做到这一点?提前致谢!
【问题讨论】:
标签: php laravel laravel-5 relationship