LoginSignup
0
0

More than 1 year has passed since last update.

Laravel9 Eloquent ORMでCAST&$visibleプロパティの巻

Last updated at Posted at 2023-03-10

###テーブル内のデータ”E2201”を取得するときに苦労したことメモ
####データベーステーブルの全中身をJSON形式で取得

public function readTable()
{
$list = \App\Models\Xxxtb::all();
return response()->json(['lists' => $list]);

XxxtbControllerで上記JSON取得を記述し、それをXxxtb.blade.phpに出力する。超簡単!ところが
⇒Xxxtbs実際のテーブルのコード列に入っている’gkno’のデータが
22E01⇒220
22E02⇒2200
22E03⇒22000......
22E10⇒220000000000
22E017⇒2200000000000000000
というデータとしてJSONの中に納まっている。
どうやら数値としてパース解釈されているらしい。
しかも自分でjson_encode();とかしている訳ではない。
もちろんDBのデータ型もCHAR型。
途方に暮れた。で見つけた!
Laravel9日本語マニュアル
MODELで以下のようにしてJSON化すれば解決!

$visibleプロパティを使用して、モデルの配列とJSON表現に含める必要のある属性を定義する。モデルが配列またはJSONに変換されると、$visible配列に存在しないすべての属性が非表示になります。

class GakuseiTb extends Model
{
    
    use HasFactory;
    protected $connection = 'sqlsrv2' ;
    protected $table = 'Xxxtb';
    protected $primaryKey = 'gkno';
    protected $updated_at = 'kodate';
    const CREATED_AT = Null;
    protected $visible = [
        'gkno',
        'nname',
        'ename',
        'sex',
        'nen',
        'seinenymd'
    ];
    protected $casts = ['gkno' =>'string',
                        'seinenymd'=> 'date:Y-m-d',
                        'nymd' => 'date:Y-m-d',
                        'symd'=> 'date:Y-m-d',
                        ];




    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
    }
   
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0