dallion
dallion

Reputation: 195

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.

Upvotes: 3

Views: 3723

Answers (3)

Dominique Lorre
Dominique Lorre

Reputation: 1168

The problem is that with() is static, so you need to add a static method to set the table name, and override getTable:

protected static $globalTable = 'defaultName' ;

public function getTable() {
    return self::$globalTable ;
}
public static function setGlobalTable($table) {
    self::$globalTable = $table;
}

Then you call:

MyModel::setGlobalTable('table02') ;

Upvotes: 1

tanteng
tanteng

Reputation: 668

just like this:

public function detail()
{
    return $this->myHasOne(Circle::class, 'group_id', 'group_id', 't_group_' . hashID($this->group_id, 20));
}

public function myHasOne($related, $foreignKey = null, $localKey = null, $table)
{
    $foreignKey = $foreignKey ?: $this->getForeignKey();

    $instance = (new $related)->setTable($table);

    $localKey = $localKey ?: $this->getKeyName();

    return new HasOne($instance->newQuery(), $this, $instance->getTable() . '.' . $foreignKey, $localKey);
}

Upvotes: 2

Mahdi Younesi
Mahdi Younesi

Reputation: 7499

what if you fresh the instance after get, before where

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

$ad->refresh();
$data = $ad->where('user_id', '=', Auth::user()->id)->with('infoDetails')->get();

Upvotes: 1

Related Questions