简体   繁体   English

无法访问Laravel中的对象属性

[英]Can't access object property in Laravel

I started learning Laravel since yesterday and face some difficulties to get property of an object. 从昨天开始,我开始学习Laravel,并且在获取对象的属性方面遇到一些困难。

Here is the class (created with artisan ) : 这是课程(由artisan创建):

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    public $description;
    public $completed;
    public $timestamps = false;

    public function isComplete()
    {
        return $this->completed;
    }
}

And here is the issue : 这是问题所在:

>>> $tasks = App\Task::all();
=> Illuminate\Database\Eloquent\Collection {#654
     all: [
       App\Task {#652
         id: "1",
         description: "Learn Laravel",
         completed: "0",
       },
     ],
   }
>>> $tasks[0]->id
=> 1
>>> $tasks[0]->description
=> null

Why can I access the id but can not access the description ? 为什么我可以访问id但不能访问description

Field description is empty because you have public field in your model with the same name: 字段description为空,因为您的模型中具有相同名称的公共字段:

public $description;

Just remove it and you will be able use value of the field description from the DB table of your model. 只要删除它,您就可以使用模型的数据库表中字段description值。

You have to make your model property as follow 您必须使模型属性如下

protected $table = 'your table name';
protected $primaryKey = 'id';
protected $fillable = ['description','completed'];

I hope this will work for you. 希望这对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM