繁体   English   中英

Laravel&Eloquent:关系中的setTable()

[英]Laravel & Eloquent : setTable() in relationships

我在雄辩的通话中使用setTable()方法,因为我正在使用INFO_MATCH_[group_id]类的表,其中group_id特定于一组用户。 INFO_[group_id] 我可以这样做一个简单的select语句:

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

这很好。 InfoMatch模型具有如下定义的关系:

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

当我尝试拨打电话时:

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

它最终会出错。 您能否建议如何在关系函数中动态设置表名? 谢谢。

如果你新鲜的实例后得到的,之前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();

像这样:

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM