简体   繁体   中英

Foreign Key relations not working in laravel

I have made two tables Inventories and Inventory_images. Primary key of Inventory table is the foreign key of inventory_images table now i am trying to fetch all the images of same inventory but getting error. Here's my code

Inventory Model:

/**
 * 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 Model:

protected $table = 'inventory_images';

protected $PrimaryKey = 'id';

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

Controller:

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

Can some one please help me find out the issue

You are making some mistakes in your code which you should resolve first (and which might help you solve your problem).

First, the variable name to overwrite the primary key should be $primaryKey and not $PrimaryKey (variable names normally always start with a small letter. This should not have any influence though, since Laravel assumes the primary key field to be named id anyway.

More importantly, you are in both cases using the belongsTo method, although in one case it should be hasMany . In a 1-n relation the parent model should return the hasMany relationship, and the child model (which holds the column with the foreign key) the belongsTo .

Furthermore, the second argument of the hasMany or belongsTo method is the foreign key column name, in case it is different of the snake case representation of the model (appended by _id ). So IF your inventory_images table has a differently named foreign key column other than inventory_id , you need to pass along the second argument with the correct name. I assume that your foreign key name is i_id , so you need to pass it to both functions.

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

Please check if this works:

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

And the child table:

protected $table = 'inventory_images';

protected $primaryKey = 'id';

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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