2017-08-08 7 views
0

我制作了两个表库存和Inventory_images。 Inventory表的主键是inventory_images表的外键,现在我试图获取同一库存的所有图片但出现错误。 这里是我的代码不在laravel中工作的外键关系

库存模型:

/** 
* 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'); 
} 

InventoryImage型号:

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); 

能有人请帮我找出问题

+0

有什么错误? – Nima

+0

调用模型[App \ Inventory]上的未定义关系[测试]。 这是错误 – Mohsin

回答

0

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

首先,覆盖主键变量的名称应该是$primaryKey而不是$PrimaryKey(变量名通常总是用小字母开头。 这应该不会有什么影响,不过,因为Laravel假定要命名的主键字段id反正。

更重要的是,你在使用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'); 
} 
+0

我试过你的解决方案,但现在它给了我另一个错误 – Mohsin

+0

试图获得非对象的属性 – Mohsin