繁体   English   中英

外键关系在Laravel中不起作用

[英]Foreign Key relations not working in laravel

我做了两个表Inventory和Inventory_images。 库存表的主键是库存表图像的外键,现在我正在尝试获取相同库存的所有图像,但会出错。 这是我的代码

库存模型:

/**
 * The table name that should be hidden from other modules
 */
protected $table = 'inventories';


protected $PrimaryKey = 'id';

public function test(){
    return $this->belongsTo('App\InventoryImage', 'i_id');
}

库存图片模型:

protected $table = 'inventory_images';

protected $PrimaryKey = 'id';

public function inv_det(){
    return $this->belongsTo('App\Inventory', 'id');
}

控制器:

$inventory = Inventory::with('test')->orderBy('id', 'DESC')->paginate('10');
        dd($inventory);

可以请一个人帮我找出问题所在吗

您在代码中犯了一些错误,应该首先解决(这可能会帮助您解决问题)。

首先,要覆盖主键的变量名应该是$primaryKey而不是$PrimaryKey (变量名通常总是以小写字母开头。尽管如此,这应该没有任何影响,因为Laravel假定主键字段始终以id命名。

更重要的是,在两种情况下, belongsTo使用belongsTo方法,尽管在一种情况下,应为hasMany 在1-n关系中,父模型应返回hasMany关系,而子模型(包含带有外键的列)应belongsTo

此外,hasMany或belongsTo方法的第二个参数是外键列名称,以防与模型的蛇形表示形式不同(由_id附加)。 因此,如果您的inventory_images表具有一个除inventory_id之外的不同名称的外键列,则需要使用正确的名称传递第二个参数。 我假设您的外键名称是i_id ,所以您需要将其传递给两个函数。

https://laravel.com/docs/5.4/eloquent-relationships#one-to-many

请检查是否可行:

/**
 * The table name that should be hidden from other modules
 */
protected $table = 'inventories';


protected $primaryKey = 'id';

public function test(){
    return $this->hasMany('App\InventoryImage', 'i_id');
}

和子表:

protected $table = 'inventory_images';

protected $primaryKey = 'id';

public function inv_det(){
    return $this->belongsTo('App\Inventory', 'i_id');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM