标签: laravel-models

如何在子类中扩展 PHP Laravel 模型的可填充字段?

我尝试使用其他一些字段扩展 extintig \xcb\x99PHP` Laravel 模型,但我没有找到正确的解决方案。我使用 PHP 7.1 和 Laravel 6.2

\n\n

这是我的代码,解释了我想要做什么。

\n\n

原型号:

\n\n
<?php\nnamespace App;\n\nuse App\\Scopes\\VersionControlScope;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Product extends Model\n{\n    protected $fillable = [\n        \'product_id\',\n        \'name\',\n        \'unit\',\n        // ...\n    }\n\n    // ... relations, custom complex functions are here\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

正如我想象的那样如何扩展原始模型:

\n\n
<?php\nnamespace App;\n\nclass ProductBackup extends Product\n{\n    protected $fillable = array_merge(\n        parent::$fillable,\n        [\n            \'date_of_backup\',\n        ]\n    );\n\n    // ...\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但现在我收到Constant expression contains invalid operations错误消息。

\n\n

$fillable我可以在子类中扩展显示原始模型的数组吗?

\n

php laravel php-7.1 laravel-6 laravel-models

7
推荐指数
1
解决办法
4317
查看次数

Laravel 在单个注入模型上进行预加载

我正在尝试在我的项目中使用 Laravel 预加载,并且我已经阅读了有关它的文档。文档中的每个示例都是关于使用预加载获取模型的所有实例。但这只是获取所有实例而不仅仅是单个模型吗?考虑一下:

public function single(Coin $coin)
{
    $coin = $coin->with('exchanges')->get();
    return view('public.coin',compact('coin'));
}
Run Code Online (Sandbox Code Playgroud)

它是一种控制器方法,它使用路由绑定加载单个硬币并注入实例,我正在尝试急切加载该硬币的关系。但是当我在刀片视图文件中访问 $coin 时,我会得到所有硬币的列表。所以我不能急切地加载注入的模型实例?!

eager-loading eloquent laravel-7 laravel-models

2
推荐指数
1
解决办法
1480
查看次数

Laravel 模型:启动特征和模型

我有一些 Laravel 模型使用下一个 Trait 来调用模型的 boot 方法:

<?php

namespace App\Traits;

use Illuminate\Support\Str;

trait Uuids
{
  /**
   * Boot function from Laravel.
   */
  protected static function boot()
  {
    parent::boot();
    static::creating(function ($model) {
      if (empty($model->{$model->getKeyName()})) {
        $model->{$model->getKeyName()} = Str::uuid()->toString();

        if ($model->consecutive) {
          $model->consecutive = $model->max("consecutive") + 1;
        }
      }
    });
  }

  /**
   * Get the value indicating whether the IDs are incrementing.
   *
   * @return bool
   */
  public function getIncrementing()
  {
    return false;
  }

  /**
   * Get the auto-incrementing key type.
   * …
Run Code Online (Sandbox Code Playgroud)

laravel laravel-models

2
推荐指数
1
解决办法
4116
查看次数

如何让 Laravel 中每个新创建的表的所有列默认可填充

在每个 Laravel 模型中,我想像下面这样声明可填充。

protected $fillable = [
    'object_name','attributes','item','cost','status','category',
    'object_id','status','customer_id','provider_id'
       
];
Run Code Online (Sandbox Code Playgroud)

之后,我可以在数据库中插入值。有什么方法可以使每个新创建的表的所有列都可填充,还是我每次都需要更改它?

eloquent laravel-5 laravel-models laravel-8

0
推荐指数
1
解决办法
5252
查看次数