【发布时间】: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->short_content? -
@linktoahref 尝试了 short_Content 和 short_content 两者,同样的错误
-
你为什么在你的控制器方法中两次传递
$articles?一次就够了。