php - 将构造函数添加到模型时,Eloquent 无法识别可填充字段

标签 php laravel laravel-5 eloquent laravel-5.4

我的模型类别如下:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * @var $fillable
     */
    protected $fillable = array('title', 'slug' , 'descriptoin', 'cover', 'logo', 'parent_id');

    /**
     * @var $category_logo_pathp
     */
    protected $category_logo_path ;

    /**
     * @var $category_cover_path
     */
    protected $category_cover_path ;

    /**
     * constructor
     */
    function __construct()
    {
        $this->category_cover_path = public_path() . '/upload/image/category/cover/';
        $this->category_logo_path = public_path() . '/upload/image/category/logo/';
    }

    /**
     * relation with itself
     */
    public function parent()
    {
        return self::where('id', $this->parent_id)->first();
    }

    public function coverPath()
    {
        return $this->category_cover_path;
    }

    public function logoPath()
    {
        return $this->category_logo_path;
    }
}

当将具有正确数据的类别实例插入数据库时​​,Eloquent 无法识别模型的可填充字段,然后抛出 Illuminate\Database\QueryException 但当我从类别模型中删除构造函数时,它可以工作使用 Eloquent 可以识别精细字段和可填写字段。这是什么原因造成的?

最佳答案

当然,您应该运行父构造函数,并且使用默认模型签名可能是相当合理的,因此您的构造函数应如下所示:

public function __construct(array $attributes = [])
{
   parent::__construct($attributes);
   $this->category_cover_path = public_path() . '/upload/image/category/cover/';
   $this->category_logo_path = public_path() . '/upload/image/category/logo/';
}

关于php - 将构造函数添加到模型时,Eloquent 无法识别可填充字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44359161/

相关文章:

php - laravel 获取多个结果集

php - 如何避免多次加载 jQuery 脚本?

javascript - PHP 无法添加更多行(表单重复器)

laravel - 如何在 Laravel 4 中获取 @if 语句(Blade)中的当前 URL?

mysql - 根据用户的技能以及 Laravel 查询生成器中的匹配技能来选择用户

php - 从 Controller 类 Laravel 访问模型方法

facebook - URL 被阻止 : This redirect failed because the redirect URI is not whitelisted. ...(本地主机 Web 应用程序)

php - 寻找Mysql中位数

javascript - PHP 内嵌框架 |每 X 次刷新一次并翻阅页面数组

laravel - 在 VueJs 中使用 Laravel 的 Gate/Authorization