我试图建立仓库(当然非常简单)。我有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


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

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

最佳答案

使用数据透视表意味着您的关系是多对多的。根据Laravel documentation,您在模型中的关系都应定义为belongsToMany

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

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


如果您不打算建立多对多关系,则您的组应该只有一个商店,而您的商店可以有许多组。然后,这意味着您只需要在groups表上的store_id列。这就是Eloquent目前正在寻找的东西。

关于php - BelongsToMany具有许多Laravel SQLSTATE [42S22],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31912006/

10-14 15:01