【发布时间】:2020-07-05 14:57:12
【问题描述】:
我试图从带有数据透视表 (belongToMany) 的项目中获取“diversities()”。
我错过了什么?:
** 客户端工作正常,项目和客户端是相同的(几乎)。 我得到的错误是
未找到基表或视图:1146 表“restigo_spm.diversity_item”不存在
而且我在代码中的任何地方都没有diversity_item,为什么要搜索它?
客户:
class Client extends Model
{
protected $fillable = ['name', 'diversity_id', 'type', 'enable'];
public function diversities()
{
return $this->belongsToMany('App\Models\Diversity');
}
}
客户端架构:
Schema::create('clients', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('client_diversity_id')->nullable();
$table->string('name')->unique();
$table->enum('type', ['restaurant', 'coffee', 'bar']);
$table->boolean('enable');
$table->timestamps();
});
ClientDiversity(枢轴):
class ClientDiversity extends Model
{
protected $table = 'client_diversity';
protected $fillable = ['diversity_id', 'client_id'];
}
ClientDiversitySchema:
Schema::create('client_diversity', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('client_id')->nullable();
$table->unsignedInteger('diversity_id')->nullable();
$table->timestamps();
});
项目:
class Item extends Model
{
protected $fillable = ['name', 'diversity_id', 'catalog_number', 'price', 'has_vat', 'enable'];
public function diversities()
{
return $this->belongsToMany('App\Models\Diversity');
}
}
ItemSchema:
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('item_diversity_id')->nullable();
$table->string('name');
$table->string('catalog_number')->unique();
$table->integer('price');
$table->boolean('has_vat');
$table->boolean('enable');
$table->timestamps();
});
多样性:
class Diversity extends Model
{
protected $fillable = ['name', 'item_id', 'client_id', 'enable'];
public function clients()
{
return $this->belongsToMany('App\Models\Client');
}
public function items()
{
return $this->belongsToMany('App\Models\Item');
}
}
DiversitySchmea:
Schema::create('diversities', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->boolean('enable');
$table->timestamps();
});
这就是我所说的。 ClientControl 代码完全相同并且可以工作,但 Item 不能。 项目控制器:
class ItemController extends Controller
{
public static function index()
{
$items = Item::with('diversities')->get();
return new ItemCollection($items);
}
【问题讨论】:
标签: mysql laravel laravel-5 eloquent has-and-belongs-to-many