Sunday, March 19, 2017

one to many relationship with eloquent with laravel framework

I have a Model called Catparent and another Model called Category

class Category extends Model
{
    public function catparent() {
        return $this->belongsTo('App\Catparent','parent_id','id');
    }
}
class Catparent extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'status',
    ];

    public function category() {
        return $this->hasMany('App\Category');
    }
}

>>> $cat = App\Catparent::find(1);
=> App\Catparent {#628
     id: 1,
     name: "Electronics",
     active: "Inactive",
     created_at: "2017-03-19 12:43:10",
     updated_at: "2017-03-19 12:43:10",
   }

    >>> $cat->category;
    Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.catparent_id' in 'where clause' (SQL: select * from `categories` where `categories`.`catparent_id` = 1 and `categories`.`catparent_id` is not null)'
    >>>

Eloquent is looking for catparent_id while Categories table is having parent_id column as a foreign key to Catparent table

i have passed this through an argument in hasMany() method but still Eloquent is looking for catparent_id instead of parent_id

is there anything i am missing regarding this?



via Rishabh Gusain

Advertisement