Tuesday, March 14, 2017

Laravel & Eloquent : setTable() in relationships

I'm using the setTable() method on eloquent calls because I'm using tables like INFO_MATCH_[group_id] where group_id is specific to a group of users. The same applies to the table INFO_[group_id]. I can do a simple select statement like this:

$ad = new InfoMatch();
$ad->setTable('INFO_MATCH_'.Auth::user()->group_id);
$data = $ad->get();

This works fine. The InfoMatch model has a relationship defined like:

public function infoDetails() {
    return $this->belongsTo(Info::class, 'info_id', 'id');
}

When I try to make a call like:

        $ad = new InfoMatch();
        $ad->setTable('INFO_MATCH_'.Auth::user()->group_id);
        $data = $ad->where('user_id', '=', Auth::user()->id)->with('infoDetails')->get();

it ends up with an error. Could you advise how to dynamically set the table name in the relationship function? Thanks.



via DavidN

Advertisement