我试图从带有枢轴表(belongToMany)的项目中获得“多样性()”。
我少了什么?
**客户端工作正常,项目和客户几乎相同(几乎)。我得到的错误是
找不到基表或视图: 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');
}
}ClientSchema:
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没有。ItemController:
class ItemController extends Controller
{
public static function index()
{
$items = Item::with('diversities')->get();
return new ItemCollection($items);
}发布于 2020-07-05 15:15:45
因为下面的方法。
public function diversities()
{
return $this->belongsToMany('App\Models\Diversity');
}您使用的是belongsToMany,它是多到多的关系。由于您没有显式地定义中间表的表名,所以它根据命名约定创建它。它假设中间表是第一个diversity + _和item的表。
您可以使用client_diversity作为diversities方法的第二个参数。
正如文档中所述
如前所述,要确定关系的连接表的表名,雄辩者将按字母顺序加入两个相关的模型名称。但是,您可以重写此约定。为此,可以向belongsToMany方法传递第二个参数:
https://stackoverflow.com/questions/62742334
复制相似问题