【问题标题】:Call to undefined method Illuminate\Database\Query\Builder::with()调用未定义的方法 Illuminate\Database\Query\Builder::with()
【发布时间】:2020-05-27 02:47:14
【问题描述】:

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

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');
    }
}

gamelist.blade.php

@foreach ($homes as $home)
    <tr>
      <td>{{ $home->id }}</td>
      <td>{{ $home->name }}</td>
      <td>{{ $home->categories->name}}</td>
      <td>{{ $home->price }} €</td>

有人可以帮助我吗?谢谢

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    with 用于预先加载 Eloquent 关系。通过调用DB::table,您决定改用查询生成器,而这个不能使用 Eloquent 关系。

    你应该替换

    $home = DB::table('products')->with(['categories']);
    

    通过

    $home = Product::with('categories')->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 2020-01-04
      • 2018-10-03
      • 1970-01-01
      • 2019-04-02
      • 2016-11-25
      • 2017-07-19
      相关资源
      最近更新 更多