Eloquent在多对多关系中查询错误的表

时间:2017-09-17 07:47:17

标签: eloquent laravel-5.4 laravel-eloquent

我在多对多关系中遇到麻烦。查询关系时(在修补程序中测试)我收到sql触发的错误消息,显示错误表上的查询。

我的模特:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Slideshow extends Model
{
    public function pictures ()
    {
        return $this->hasMany(Picture::class);
    }
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class Picture extends Model
{

    public function slideshows ()
    {
        return $this->belongsToMany(Slideshow::class,'slideshowpictures')->withPivot('order')->withTimestamps();
    }
}

我对此关系的迁移:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateSlideshowpicturesMigration extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up ()
    {
        $tablename = 'slideshowpictures';
        Schema::create($tablename, function (Blueprint $table)
        {
            $table->integer('slideshow_id')->unsigned();
            $table->integer('picture_id')->unsigned();
            $table->integer('order')->unsigned();
            $table->timestamps();
        });
        Schema::table($tablename, function ($table)
        {
            $table->foreign('slideshow_id')->references('id')->on('slideshows')->onDelete('cascade');
            $table->foreign('picture_id')->references('id')->on('pictures')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down ()
    {
        Schema::dropIfExists('slideshowpictures');
    }
}

现在修补我得到以下错误:

>>> $slide =Slideshow::all()->first();
=> App\Slideshow {#751
     id: 1,
     name: "1",
     occasion_id: 1,
     created_at: "2017-09-16 19:01:59",
     updated_at: "2017-09-16 19:01:59",
   }
>>> $slide->pictures()->exists();
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pictures.slideshow_id' in 'where clause' (SQL: select exists(select * from `pictures` where `pictures`.`slideshow_id` = 1 and `pictures`.`slideshow_id` is not null) as `exists`)'
>>> $slide->pictures();
=> Illuminate\Database\Eloquent\Relations\HasMany {#830}

我还没找到答案,希望你能帮我弄清楚它为什么从我的照片表中选择,而不是我创建的联结表。

0 个答案:

没有答案