Question

I am trying to build a self join in Laravel. I wish to compare 2 columns in the same table.

When I write this in my controller:

$char_name_obj = User::find($user->id)->characters()->where('lord_id', '=', 'id')->get();

lord_id is one column, id is the other column in the same table named characters. This returns nothing. I am sure I need to do a self join to be able to achieve this.

Character model:

class Character extends Eloquent {

    protected $table = 'characters';

    protected $fillable = array('lord_id','char_name', 'char_dynasty', 'picture');

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function Titles()
    {
        return $this->hasMany('Title');
    }

    public function LordCharID()
    {
        return $this->has_one('Character');
    }
}

I don't know how to use the last function LordCharID().

Was it helpful?

Solution

has_one is the Laravel 3 function; so if you're using Laravel 4, you need to use hasOne

You can use whereRaw to compare columns:

User::find($user->id)->characters()->whereRaw('lord_id = id')->get();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top