BelongToMany有很多Laravel SQLSTATE [42S22]

时间:2015-08-10 05:12:07

标签: php mysql laravel eloquent

我试图建立仓库(当然非常简单)。我有3个表:

存储表

class CreateStoresTable extends Migration
{

public function up()
{
    Schema::create('stores', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('user_id');
        $table->timestamps();
    });
}      

群组表:

 public function up()
{
    Schema::create('groups', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('visible');
        $table->timestamps();
    });
}

一个数据透视表group_store:

public function up()
{
    Schema::create('group_store', function(Blueprint $table) {
        $table->integer('group_id')->unsigned()->index();
        $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
        $table->integer('store_id')->unsigned()->index();
        $table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');
    });
}

商店模式 - :

class Store extends Model
{
protected $table='stores';
protected $fillable = array('name','user_id');

public function group(){
    return $this->hasMany('App\Group');
}
}

群组模型

class Group extends Model
{
protected $table='groups';
protected $fillable = array('name','visible');

public function store(){
    return $this->belongsToMany('App\Store');
}
}

当我在修补匠中使用它时

$group=App\Group::find(4)
$group->store()->get() // and is working as it should

但是当我尝试反向时

$store=App\Store::first()
$store->group()->get() //i get this error message

Illuminate \ Database \ QueryException,带有消息' SQLSTATE [42S22]:找不到列:1054未知列' groups.store_id'在' where子句' (SQL:从groups中选择* groupsstore_id = 3和groupsstore_id不为空)'

我试图理解为什么雄辩在群组表中搜索store_id ...

1 个答案:

答案 0 :(得分:1)

使用数据透视表意味着您的关系是多对多的。根据{{​​3}},您的模型中的关系应定义为belongsToMany

class Store extends Model
{
    protected $table='stores';
    protected $fillable = array('name','user_id');

    public function group(){
        return $this->belongsToMany('App\Group');
    }
}

如果您不打算建立多对多的关系,那么您的论坛应该只有一个商店,而您的商店可以有多个商店。这意味着您只需要在group表上添加store_id列。这就是Eloquent现在正在寻找的。