Laravel 5雄辩的关系属于ToMany

时间:2015-12-23 17:11:11

标签: laravel-5 laravel-5.1

我有两张桌子。

(图片)

+----+------------+-------------------------------+
| id | picture_id |       picture_file_name       |
+----+------------+-------------------------------+
|  1 |         13 | 2015-12-22-19-00-15-82823.jpg |
|  2 |         13 | 2015-12-22-19-00-15-82234.jpg |
+----+------------+-------------------------------+

(电动机)

+----+------------+-------+
| id | picture_id | name  |
+----+------------+-------+
|  1 |         13 | John  |
|  2 |         0  | Chris |
+----+------------+-------+

我有两个模特。

(电动机)

class Motors extends Eloquent
{
    protected $table = 'motors';
    public function picture(){
        return $this->belongsToMany('App\Pictures','picture_id','picture_id'); // Here is the problem, but I don't know what is it.
    }
}

(图片)

class Pictures extends Eloquent
{
    protected $table = 'pictures';
    public function motors(){
        return $this->hasMany('App\Motors');
    }    
}

(控制器)

class TestController extends Controller
{
    public function found(Request $request) {
        $q = Motors::query();
        // ... queries
        $motors = $q->orderBy('id', 'DESC')->paginate(14);  
        $motors->load('picture');
        //dd($motors);
        return view('pages.motors_found', compact('motors'));
    }
}

(视图)

@foreach ($motors as $motor)
    {{ $motor->name }}
    @if (!empty($motor->picture_id))
        <ul>
        @foreach($motor->picture as $row)                                    
                <li>{{ $row->picture_file_name }}</li>                                    
        @endforeach
        </ul>
    @endif
@endforeach

(错误信息)

QueryException in Connection.php line 651:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laramotor.picture_id' doesn't exist (SQL: select `pictures`.*, `picture_id`.`picture_id` as `pivot_picture_id`, `picture_id`.`pictures_id` as `pivot_pictures_id` from `pictures` inner join `picture_id` on `pictures`.`id` = `picture_id`.`pictures_id` where `picture_id`.`picture_id` in (3025, 3015, 3014, 3013, 3012, 3011, 3010, 3009, 3008, 3007, 3006, 3005, 3004, 3003))

它回复了一个错误,可能是什么错误? 我想要回显一下属于给定电机的所有图片的picture_file_name。 在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

除了belongsToMany方法中参数的错误使用外,您的关系定义中存在问题。

模型关系

由于电机至少可以有一张图片,并且图片可能只属于一种类型的电机,因此您的关系应该如下:

Motor 有很多图片

[逆]图片属于电机

雄辩的关系

电机型号:

class Motors extends Eloquent //normally a model name should be singular
{
    protected $table = 'motors';
    public function picture(){
        return $this->hasMany('App\Pictures'); 
    }
}

图片模型:

class Pictures extends Eloquent
{
    protected $table = 'pictures';
    public function motors(){
        return $this->belongsTo('App\Motors');
    }    
}