[英]Laravel eloquent UUID in a pivot table
這個問題是這樣的: laravel uuid not shown in query 。 但是,這個問題的不同之處在於該表是一個帶有id
字段的數據透視表,使用通過 MySQL 觸發器在插入時生成的 UUID。
我不想為該數據透視表創建另一個模型來為它提供類似問題答案中考慮的解決方案。 那么,有沒有辦法從與之相關的另一個模型中執行數據透視表的類型轉換?
我想這可能是你想要的:
在定義 BelongsToMany 關系的模型中添加此屬性:
protected $casts = ['relationName.pivot.id' => 'string'];
更新
我想我們可以在這里使用php7.0
的匿名類,而不是為樞軸創建模型類:
我沒有測試這段代碼,所以我不知道它是否有效,這只是一個想法
public function activeStatuses()
{
return $this->belongsToMany('ModelName')
->using(class_basename(new class extends \Illuminate\Database\Eloquent\Relations\Pivot {
protected $casts = ['id' => 'string'];
}));
}
通常我更願意為數據透視表創建模型或簡單地使用數據透視類
這個對我有用:
// use Illuminate\Database\Eloquent\Relations\Pivot;
return $this->belongsToMany(Vendor::class, 'vendors_has_geo_cities', 'city_id', 'vendor_id')
->using(new class extends Pivot {
use UuidTrait;
});
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
trait UuidTrait
{
public function initializeUuidTrait(): void
{
$this->setIncrementing(false);
$this->setKeyType('string');
}
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function bootUuidTrait()
{
self::creating(function (Model $model) {
$model->setAttribute($model->getKeyName(), Str::orderedUuid());
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.