【发布时间】:2020-08-05 18:31:00
【问题描述】:
根据this issue,在Laravel上使用自定义方法名定义多态关系时,morphTo方法的name参数不能按预期工作,我们假设一个简单的多态表结构:
posts
id - integer
name - string
users
id - integer
name - string
images
id - integer
url - string
imageable_id - integer
imageable_type - string
还有这个模型结构:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
// ...
// It doesn't work as expected
public function picturable1()
{
return $this->morphTo('imageable');
}
// It doesn't work as expected
public function picturable2()
{
return $this->morphTo('imageable', 'imageable_type', 'imageable_id');
}
// It works unexpectedly
public function picturable3()
{
return $this->morphTo(null, 'imageable_type', 'imageable_id');
}
}
加载这些关系时:
$image = \App\Image::with('picturable1')->find(1);
$image->picturable1; // exists and returns null but imageable instance was expected
$image->imageable; // returns imageable instance unexpectedly
$image = \App\Image::with('picturable2')->find(1);
$image->picturable2; // exists and returns null but imageable instance was expected
$image->imageable; // returns imageable instance unexpectedly
$image = \App\Image::with('picturable3')->find(1);
$image->picturable3; // returns imageable instance as expected
$image->imageable; // doesn't exists as expected
所以问题是,morphTo 方法的名称参数的用例是什么?
以及像上面的示例那样自定义关系名称的正确方法是什么?
【问题讨论】:
-
您能提供您的
Post和User模型吗? -
@manzor 这只是 Laravel 文档中的一个示例,您可以在此处找到
Post和User示例代码:laravel.com/docs/7.x/…
标签: laravel eloquent eloquent-relationship polymorphic-relationship