php - 调用未定义的方法 Illuminate\Database\Query\Builder::with()
问题描述
我正在尝试显示类别的名称,但出现此错误:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::with()
管理员控制器.php
public function gamelist()
{
$categories = Category::all();
$home = DB::table('products')->with(['categories']);
return view('admin.gamelist', ['categories' => $categories, 'home' => $home, 'mode' => 'admin']);
}
产品.php
class Product extends Model
{
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
}
游戏列表.blade.php
@foreach ($homes as $home)
<tr>
<td>{{ $home->id }}</td>
<td>{{ $home->name }}</td>
<td>{{ $home->categories->name}}</td>
<td>{{ $home->price }} €</td>
有人能帮我吗?谢谢
解决方案
with
用于预先加载 Eloquent 关系。通过调用DB::table
,您决定改用查询构建器,而这个不能使用 Eloquent 关系。
你应该更换
$home = DB::table('products')->with(['categories']);
经过
$home = Product::with('categories')->get();
推荐阅读
- flutter - 如何在 TabBarView 中通过 MaterialPageRoute 导航?
- java - 我不知道在这些位置的 else 句中还能放什么
- excel - Power Query - 会计日历 445 本月周
- javascript - 使用 JS 分配渐变在动态生成的渐变上失败
- python - 在lambda函数python中使用传入if语句
- lit-element - 点燃元素中的 MDC 数据表
- javascript - 如何使用对象 JavaScript 遍历列表
- java - Maven TestNG - 编辑执行结果的控制台输出
- vb.net - 如何从 vb.net 中的二进制文件中读取 vb6 定长字符串
- javascript - Vonage Video API 中未显示视频开/关按钮