سؤال

When two tables has relation with same column name on indexes, i couldn't get joined table until i change main table field just 'id'. I cannot use query builder; must found solution on eloquent orm.

Main table,

product_id, ...

Sub table,

sub_product_id, product_id, ...

These are models,

require_once(APPPATH . 'models/connection.php');

use Illuminate\Database\Eloquent\Model as Eloquent;

class Credit extends Eloquent {

    public $timestamps = false;

    public $table = 'tbl_credit';


    public function periods() {

        return $this->hasMany('Period', '**product_id**');
    }
}

and sub model,

require_once(APPPATH . 'models/connection.php');

use Illuminate\Database\Eloquent\Model as Eloquent;


class Period extends Eloquent {

    public $timestamps = false;

    public $table = 'tbl_credit_period';


    public function credit() {
        return $this->belongsTo('Credit', '**product_id**');
    }
}

Code is like that

Credit::with('periods')->get()->toArray()

gives result as

array(product_id => .., periods => null)

If i change credit table primary key from product_id to id then it works.

هل كانت مفيدة؟

المحلول

The problem is not naming 1st table key and 2nd table foreign key the same, but that you don't comply the naming convention for Eloquent models.

Eloquent will check for the id as a primary key if you don't specify it explicitly, so this should work for you (though I suggest not naming those columns the same anyway):

// Credit model
protected $primaryKey = 'product_id';

To make it clear - your code is not joining tables but runs another query with where in clause, and Laravel should fetch the related rows correctly. The problem is with matching fetched results to their Credit parents later, that's why you get null there.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top