2016-06-24 12 views
0

私は現在、私のデータベース内の各ポスト行がポストのIDをベースに独自のハッシュ属性を持つことになりますブログを作成しています他のセットにはSetIdAttribute()ミューテーターを使用して(インクリメント、常にユニーク)。Laravel 5.2 - バリュー

私はこの工場

$factory->define(App\Post::class, function (Faker\Generator $faker) { 
    return [ 
     'title' => $faker->sentence(mt_rand(3, 10)), 
     'content' => join("\n\n", $faker->paragraphs(mt_rand(3, 6))), 
     'author' => $faker->name, 
     'category' => rand(1, 20), 
    ]; 
}); 

を実行すると、この私のPostモデル

<?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($値)関数が呼び出されつつあるが、私のハッシュ属性が設定されていません。私はそれが上書きされているかどうかわからない。

私は

public function setTitleAttribute($value) 

機能にライン

$this->attributes['hash'] = Hashids::encode($value); 

を移動し、タイトルをエンコードする場合、それは正常に動作属性が、私は「ID」属性をエンコードしたいです。どのように私はこれをやろうと思った?

答えて

2

何かを行うことができますあなたのモデルに以下を追加することができます。

/** 
* Events 
*/ 
public static function boot() 
{ 
    parent::boot(); 

    static::created(function($model) 
    { 
     $model->hash = Hashids::encode($model->id); 
     $model->slug = str_slug($model->title); 
    } 
} 
+0

私は、http(これにモデルを変更:// i.imgur.com/ivZFYCy.png)、ハッシュとスラッグは設定されていません。 – StackOverflower

+0

これを見て、$ model-> save()を追加する必要がありました。課題の終わりまで – StackOverflower

1

おそらくsetIdAttribute($value)は、これまでのIDを知らないため、挿入が実行されるまで呼び出されない可能性があります。

実際の問題は、idが挿入後まで認識されないため(auto_incrementingの場合)、同じクエリでidのハッシュを設定できないということです。

このため、ここではおそらくモデルのsavedイベントでコードを焼くことができます。そのモデルでは

は、おそらくのような...

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(); 
    }); 
}