要防止Laravel的morphMany将id转换为整数,可以通过在模型中重写getMorphs
方法来实现。以下是一个示例:
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\Relation;
class ExampleModel extends Model
{
/**
* 获取与模型相关的多态关联。
*
* @param string $name
* @param string|null $type
* @param string|null $id
* @param string|null $ownerKey
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function morphMany($related, $name, $type = null, $id = null, $ownerKey = null)
{
$instance = $this->newRelatedInstance($related);
$type = $type ?: $this->getMorphType($name);
$id = $id ?: $this->getForeignKey();
return new MorphMany(
$instance->newQuery(), $this, $type, $id, $ownerKey ?: $this->getKeyName(), $name
);
}
/**
* 获取多态关系的外键类型。
*
* @param string $name
* @return string
*/
protected function getMorphType($name)
{
if (static::$snakeAttributes) {
$name = Str::snake($name);
}
return $name.'_type';
}
}
在上面的示例中,我们重写了morphMany
方法,将$id
参数设置为null
,这样Laravel就不会将id转换为整数。同时,我们还重写了getMorphType
方法,以确保在多态关联时使用正确的关联键。
使用这个重写的模型,你就可以防止Laravel的morphMany
将id转换为整数了。