laravel - `morphTo` 方法的第一个参数的用例是什么?
问题描述
根据这个问题,在 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
?以及像上面的示例一样自定义关系名称的正确方法是什么?
解决方案
我猜该name
参数允许您自定义将存储相关模型的属性的名称。因此,在控制器中,您应该指定您期望的名称作为关系:
public function picturable1()
{
return $this->morphTo('picturable1', 'imageable_type', 'imageable_id');
// or return $this->morphTo(null, 'imageable_type', 'imageable_id');
}
public function picturable2()
{
return $this->morphTo('picturable2', 'imageable_type', 'imageable_id');
// or return $this->morphTo(null, 'imageable_type', 'imageable_id');
}
推荐阅读
- java - 如何通过读取 Java 中的控制台输入来检测按下“向上”/“向下”键?
- php - PHP对数据库的一般思考
- javascript - 如何在特定网站的 Android 后台服务中获取 http 请求?
- android - RecyclerView 在嵌套片段中不滚动
- html - 具有 srcset 的不同大小的图像在看似随机的断点处加载图像
- jquery - jQuery获取动态创建的多个(> 300)单选按钮的值
- firebase - Firebase 动态链接 CORS - XMLHttpRequest
- prolog - 为什么这些规则有效?(在序言中查找列表中的最后一个元素)
- mysql - 如何从数据库中获取每 n 个数据
- python - python - 从字符串中替换切片