Reputation: 195
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
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
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
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