gpt4 book ai didi

php - Laravel & Eloquent : setTable() in relationships

转载 作者:行者123 更新时间:2023-12-01 15:36:36 25 4
gpt4 key购买 nike

我在 Eloquent 调用中使用了 setTable() 方法,因为我使用的是像 INFO_MATCH_[group_id] 这样的表,其中 group_id 是特定于一组用户。这同样适用于表 INFO_[group_id]。我可以像这样做一个简单的选择语句:

$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();

它以错误结束。你能建议如何在关系函数中动态设置表名吗?谢谢。

最佳答案

就像这样:

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

关于php - Laravel & Eloquent : setTable() in relationships,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42782695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com