动态添加新属性到模型(Laravel)

时间:2017-04-18 13:22:56

标签: laravel eloquent

我正在使用Laravel 5.4并且似乎无法添加新属性,这里是我的代码,其中包含一个注释部分,显示的输出不会返回我添加的名为Url的新属性。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Exercice extends Model
{
    protected $table = 'exercices';
    protected $connection = 'DB_V2';
    protected $appends = ['Url'];


    public function getUrlAttribute() {
        return 'custom';
    }

    /*
    $exercise = App\Exercice::where("idExercice", 1)->get();
    dd($exercise);

          #attributes: array:15 [▼
        "idExercice" => 1
        "image1" => "160_A.jpg"
        "image2" => "a.jpg"
        "thumb1" => "v.jpg"
        "thumb2" => "c.jpg"
        "video" => "fliqz|077fzc4f478142cea8a73e586617f8a\r\n"
        "draw1" => ""
        "draw2" => ""
        "drawthumb1" => ""
        "drawthumb2" => ""
        "licno" => 1000
        "idusager" => 0
        "code_exercice" => "XAMP160"
        "shared" => "Y"
        "rank" => 99999999
      ]
      */

}

1 个答案:

答案 0 :(得分:0)

该值不会出现在对象本身的dd()中,因为该属性实际上并不存在于$attributes属性中。

如果您dd()数组或json输出,您应该看到您的值:

$exercise = App\Exercice::where("idExercice", 1)->get();
dd($exercise->toArray());