mercredi 23 décembre 2015

Laravel 5 Eloquent relationship belongsToMany

I have two table.

(Pictures)

+----+------------+-------------------------------+
| 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 |
+----+------------+-------------------------------+

(Motors)

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

I have two models.

(Motors)

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

(Pictures)

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

(The controller)

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

(The view)

@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

(The error message)

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))

It gives back an error, what could be wrong? I'd like to echo out the picture_file_name's of all pictures wich are belong to the given motors. Thanks in advance for your help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire