Php Laravel 5.2-使用SetIdAttribute()Mutator设置其他值
我目前正在创建一个博客,其中数据库中的每个帖子行都将有一个唯一的hash属性,该属性基于帖子的id(递增,始终唯一) 这是我的贴身模特Php Laravel 5.2-使用SetIdAttribute()Mutator设置其他值,php,database,laravel,Php,Database,Laravel,我目前正在创建一个博客,其中数据库中的每个帖子行都将有一个唯一的hash属性,该属性基于帖子的id(递增,始终唯一) 这是我的贴身模特 <?php namespace App; use Illuminate\Database\Eloquent\Model; use Hashids; class Post extends Model { public function setTitleAttribute($value) { $this->attributes['t
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Hashids;
class Post extends Model
{
public function setTitleAttribute($value)
{
$this->attributes['title'] = $value;
if (! $this->exists) {
$this->attributes['slug'] = str_slug($value);
}
}
public function setIdAttribute($value) {
$this->attributes['id'] = $value;
$this->attributes['hash'] = Hashids::encode($value);
}
}
正在调用setIdAttribute($value)函数,但未设置我的哈希属性。我不确定它是被覆盖了还是什么
如果我移动线
$this->attributes['hash'] = Hashids::encode($value);
到功能
public function setTitleAttribute($value)
对title属性进行编码工作正常,但我想对'id'属性进行编码。你知道我该怎么做吗?很可能在insert运行之后才调用
setIdAttribute($value)
,因为它在运行之前不知道ID
真正的问题是不能在同一个查询中设置id
的散列,因为id
在插入之后才会被知道(假设它是自动递增的)
正因为如此,您在这里可能能做的最好的事情就是在模型的保存的
事件上触发一些代码
在这个模型中,你可能可以做一些像
public static function boot()
{
parent::boot();
static::flushEventListeners(); // Without this I think we have an infinite loop
static::saved(function($post) {
$post->hash = Hashids:encode($post->id);
$post->save();
});
}
它很可能在insert运行之后才被调用,因为在此之前它不知道ID 真正的问题是不能在同一个查询中设置
id
的散列,因为id
在插入之后才会被知道(假设它是自动递增的)
正因为如此,您在这里可能能做的最好的事情就是在模型的保存的
事件上触发一些代码
在这个模型中,你可能可以做一些像
public static function boot()
{
parent::boot();
static::flushEventListeners(); // Without this I think we have an infinite loop
static::saved(function($post) {
$post->hash = Hashids:encode($post->id);
$post->save();
});
}
您可以将以下内容添加到模型中:
/**
* Events
*/
public static function boot()
{
parent::boot();
static::created(function($model)
{
$model->hash = Hashids::encode($model->id);
$model->slug = str_slug($model->title);
}
}
您可以将以下内容添加到模型中:
/**
* Events
*/
public static function boot()
{
parent::boot();
static::created(function($model)
{
$model->hash = Hashids::encode($model->id);
$model->slug = str_slug($model->title);
}
}
我把模型改成了这个(),现在散列和slug没有被设置。我需要添加$model->save();在赋值结束时,我将模型更改为this(),现在没有设置哈希和slug。我需要添加$model->save();直到作业结束