调用未定义的方法 Illuminate\Database\Query\Builder::with()

我试图显示类别的名称,但出现此错误:


BadMethodCallException

Call to undefined method Illuminate\Database\Query\Builder::with()

AdminController.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>

有人能帮我吗?谢谢


白衣染霜花
浏览 81回答 1
1回答

慕后森

with用于急切加载 Eloquent 关系。通过调用DB::table,您决定改用查询构建器,而这个不能使用 Eloquent 关系。你应该更换$home&nbsp;=&nbsp;DB::table('products')->with(['categories']);经过$home&nbsp;=&nbsp;Product::with('categories')->get();
打开App,查看更多内容
随时随地看视频慕课网APP