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

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

我想创建一个带有子菜单的动态菜单。 将是 Level1、Level2、Level3。

但是我得到这个错误: 调用未定义的方法 Illuminate\Database\Query\Builder::has_many() 和 调用未定义的方法 Illuminate\Database\Query\Builder::has_many() (视图:C:\xampp\htdocs****\resources\views\test.blade.php)

这是我目前拥有的:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class WorkoutLevel1 extends Model
{
    protected $table ='workout_level1s';

    protected $fillable = ['title','icon','order_no'];

    public function workoutlvl2(){
         return $this->has_many('WorkoutLevel2');
      }
}`

`

<?php
namespace App; 
use Illuminate\Database\Eloquent\Model;
class WorkoutLevel2 extends Model
{
   protected $table = 'workout_level2s';

   public function workoutlvl1(){
         return $this->belongs_to('WorkoutLevel1');
      }

   public function workoutlvl3(){
        return $this->has_many('WorkoutLeve3');
   }   

   protected $fillable = ['title','order_no'];
}

`

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class WorkoutLevel3 extends Model
{
    protected $table = 'workout_level3s';

    public function workoutlvl2(){
         return $this->belongs_to('WorkoutLevel2');
      }

    protected $fillable = ['title','order_no'];
}

路线:

Route::get('/menu', function () {
    $lvl1s = App\WorkoutLevel1::all();

    return View::make('test',compact('lvl1s'));
});`

观点`

<div class="categories">
            <!-- // left menu.... -->
            <ul class="main">
                @foreach($lvl1s as $lvl1)
                    <li><a href="">{{$lvl1->title}}</a></li>
                    @foreach($lvl1->workoutlvl2->take(2) as $lvl2)
                        <li><a href="">{{$lvl2->title}}</a></li>
                    @endforeach
                @endforeach
            </ul>
    </div>

错误说:

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

因此,将 has_many 替换为 hasMany(将 belongs_to 替换为 belongsTo

如果您使用 Laravel 5,请使用 hasManybelongsTo 而不是 has_many。 您还可以查看 Laravel 文档。

即使在laravel 4.2中也不是has_many,正确的用法是hasMany...