【问题标题】:Laravel accessors using Query Builder使用查询生成器的 Laravel 访问器
【发布时间】:2017-12-04 14:50:41
【问题描述】:

试图在查询生成器中获取访问器但抛出错误“Undefined property: stdClass::$shorcontent”

//controller
        public function index(){
        $articles = DB::table('articles')->paginate(10);
        return view('articles.index', ['articles' => $articles], compact('articles'));
    }

这是带有访问器的模型文件

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = [
        'user_id', 'content', 'live', 'post_on'
    ];

    protected $guarded = ['id'];

    public function getShortContentAttribute()
    {

        return substr($this->content,0, random_int(60, 150));
    }
}

这里是视图

//article/index.blade.php View
<td class="col-md-6">{{ $article->shortcontent }} </td>

当我使用 eloquent 而不是查询生成器时,同样的代码工作,就像这样

public function index()
{
    $articles = Article::paginate(10);
    return view('articles.index', ['articles' => $articles], compact('articles'));
}

【问题讨论】:

  • 试试shortContent。您肯定错过了名称中的 t。
  • @aynber 抛出错误“未定义的属性:stdClass::$shortContent”
  • 试过$article-&gt;short_content ?
  • @linktoahref 尝试了 short_Content 和 short_content 两者,同样的错误
  • 你为什么在你的控制器方法中两次传递$articles?一次就够了。

标签: php laravel accessor


【解决方案1】:

这个答案很晚,您可能已经找到了解决方案,但希望它对其他人有所帮助。

简短的回答,DB 门面无权访问模型中定义的访问器和修改器。只有模型实例生成的对象才能访问访问器和修改器。

我认为这里的问题是使用 DB 外观只会创建查询构建器,而没有对您在文章模型中设置的访问器或修改器的任何引用。 DB 门面只使用查询构建器查询数据库,并返回一个独立于文章模型的对象。

然而,模型外观将构建一个查询构建器,但创建的对象实例将可以访问访问器和修改器,因为它是 Article Model 类的对象实例。

查看这个 SO 答案: Difference between DB and Model facade

只有在您尝试从模型实例中检索属性值时才会访问访问器,例如:

$article = Article::find(1);
$shortContent = $article->short_content;

这将进一步解释here

因此,如果您希望访问访问器,则必须使用 Model 门面,即 Article::paginate(10)。

【讨论】:

    【解决方案2】:

    您缺少附加 short_content 属性。只需添加此

    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Article extends Model
    {
    
    protected $fillable = [
        'user_id', 'content', 'live', 'post_on'
    ];
    protected $appends = ['short_content'];
    protected $guarded = ['id'];
    
    public function getShortContentAttribute()
    {
    
    return substr($this->content,0, random_int(60, 150));
    
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-16
      • 2019-02-22
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 2017-04-24
      • 1970-01-01
      相关资源
      最近更新 更多