php - 这段代码“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');
我要如何设置一些默认值?谢谢你!
解决方案
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();
推荐阅读
- reinforcement-learning - TRPO - RL:我需要让一个 8DOF 机械臂移动到指定点。我需要在 Gazebo 环境中使用 OpenAI gym 来实现 TRPO RL 代码吗?
- mediawiki - 我如何上传图像并同时向它们添加货物元数据?
- javascript - Formik FieldArray 使用 Yup 进行嵌套对象验证
- javascript - 在具有角度的第二个自然获取浏览器中设置自定义标题
- graph - 图形 API 创建新组和团队 - 图形资源管理器中的“请求中的无效绑定属性名称成员”问题
- node.js - MongoDB 投影参数在 findOne() 中不起作用
- perl - Perl Net::SMTP 在调用 auth() 时/之前突然断开连接
- c# - 在 Visual Studio 中使用 DllImport 复制 DLL 的最佳实践?
- r - 根据特定条件合并两个数据集,同时保留特定列
- wordpress - Azure Web App Wordpress 如何添加虚拟目录?