简体   繁体   中英

Laravel Eloquent Relationship column not found

Can you help me with this one?

ANSWER MODEL

class Answer extends Eloquent {
    protected $primaryKey = 'ID';
    protected $table = 'answers';
    protected $fillable = array('customerID', 'agentID', 'status', 'date', 'urn_code', 'urn_id');

    public function customer(){
        return $this->hasOne('Customer');
    }
}

CUSTOMER MODEL

class Customer extends Eloquent {
    protected $connection = 'mysql';
    protected $table = 'leads';
    protected $primaryKey = 'cID';

    protected $fillable =  array('cID','title', 'first_name','last_name','address1', 'address2', 'post_code','city','phone_number');

    public function answers() {
        return $this->hasMany('Answer');
    }
}

ROUTE

Route::get('sales', function(){
    $sales = Customer::with('answers')->get()->paginate(15);

    foreach($sales as $sale)
    echo $sale->last_name . '<br />'; 

});   

and this is my error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'answers.customer_id'

It's exactly how the error says. In your answers table, Laravel is looking for a customer_id column automatically, and it doesn't exist in this case.

If your customer ID column is under a different name, you can specify it as the second parameter in the hasMany() method:

public function answers() {
    return $this->hasMany('Answer', 'my_column');
}

Also, you should probably be using a belongsTo relationship here, as pointed out by @razor.

Since you are using custom primary keys, you need to specify the local key and the foreign key.

public function answers() {
    return $this->hasMany('Answer', 'foreign_key', 'local_key');
}

Probably you'll have to update your Answer model as well (please, check out if you really need a hasOne or a belongsTo relation):

public function customer(){
    return $this->belongsTo('Customer', 'foreign_key', 'local_key');
}

You can find more info here .

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