首页 > 解决方案 > 这段代码“protected $attributes = [];”有什么用?

问题描述

我是laravel的初学者。我从 laravel 的网站https://laravel.com/docs/5.8/eloquent#default-attribute-values阅读了一些信息,它说我们可以在模型中设置一些默认属性。详细说了什么:

默认属性值 如果您想为模型的某些属性定义默认值,您可以在模型上定义 $attributes 属性:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
    /**
     * The model's default values for attributes.
     * @var array
     */
    protected $attributes = [
        'delayed' => false,
    ];
}

现在,我在 laravel 中创建了 CRUD 函数。并在数据库中设置一些示例/默认值,它是 "id"=1,"element1"="ABC","element2"="abc"。最后,我在显示表中一无所获。

Database Table:
...
public function up()
  {
    Schema::create('cruds', function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->string('element1');
      $table->string('element2');
  });
}
...
Model:CRUD
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class crud extends Model
{
    protected $timestramp = false;
    protected $primarykey = "id";
    protected $attributes =[
        'id'        => 1,
        'element1'  => "ABC",
        'element2'  => "abc",
    ];
}
View.blade.php
...
<tbody>
@foreach ($CRUDitems as $item)
  <tr>
    <th scope="row">{{ ($item->$id) }}</th>
    <td>{{ ($item->$element1) }}</td>
    <td>{{ ($item->$element2) }}</td>
  </tr>
@endforeach
</tbody>
...
CRUDController.php
...
public function index()
  {
    $CRUDitems = crud::all();
    return view('CRUD.viewTable',compact('CRUDitems')) ;
  }
...
web.php
<?php
Route::resource('/CRUD', 'CRUDController');

我要如何设置一些默认值?谢谢你!

标签: phplaravel

解决方案


You have to make an object from your model. To do so (for test purpose) let's add a route like this:

Route::get('test', 'CRUDController@test');

And in your controller add a test method like this:

public function test(){
    $crud = new Crud();
    $crud->save();
}

You can also use tinker to test your code.

type php artisan tinker in command/console and then make a new instance of your model:

$crud = new App\Crud;
$crud->save();

推荐阅读