Laravel模型问题(非对象)

时间:2017-01-04 16:37:42

标签: php laravel

我使用的是Laravel 5.3和这个型号:     

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use SoftDeletes;

    protected $table = 'categories';

    protected $fillable = [
        'name', 
        'slug',
        'description',
        'thumbnail',
        'parent',
        'created_by'
    ];

    protected $hidden = [
        'created_by'
    ];

    protected $dates = ['deleted_at'];

    public static function getSubcategories($category)
    {
        return Category::whereParent(Category::whereSlug($category)->first()->id)->get();
    }
}

它在我的localhost服务器上运行良好,但是当我在生产服务器上传它时,它会输出以下错误:

  

尝试获取非对象的属性(在线....)

就在这条线上:

return Category::whereParent(Category::whereSlug($category)->first()->id)->get();

(行被隐藏,因为这个模型有更多的功能,对于这个帖子来说太长了)

完整追踪: Full error stack trace

1 个答案:

答案 0 :(得分:0)

因为Category::whereSlug($category)->first()返回null并且您正在尝试获取该null的id。所以它的错误表明你试图得到一个非对象的属性。

我看到你正试图获得自我参考类别。你可以这样作为一种关系。

//children
public function categories()
{
    return $this->hasMany(self::class, 'parent');
}

//parent
public function parent()
{
    return $this->belongsTo(self::class, 'parent');
}

如果你想以递归方式选择,你也可以添加它。

public function parentRecursive()
{
    return $this->parent()->with('parentRecursive');
}

public function categoriesRecursive()
{
    return $this->categories()->with('categoriesRecursive');
}