繁体   English   中英

Laravel雄辩的HasMany / HasOne附加条款

[英]Laravel Eloquent HasMany / HasOne Additional On Clauses

早上好,

道歉,如果以前曾有人问过这个问题,但我们无法找到所遇到问题的任何答案。

我们正在使用一个不属于我们的旧数据库(只读),并且正在尝试使用Laravel中的Eloquent(模型)来解决一些常见问题。

是否可以设置Eloquent的Eager-loading来为HasMany / HasOne关系构建器创建其他ON子句?

请在下面看到我们在没有原始查询的情况下要实现的目标。

public function policy()
{
    return $this->hasMany(Policy::class, 'Group', 'Group')
        // This breaks as `on` isn't defined on Eloquent\Builder. Is this concept possible? Multiple on clauses
        ->on('Reference', 'Reference');
}

在我们的控制器中,我们尝试了以下操作,但也失败了。

 Vehicle::with([
        'policy' => function ($query) {
            // Model isn't instantiated yet, but we need an additional on clause here
            $query->on('Reference', 'Reference');
        }
   ]);

可以实现上述目标吗?还是必须恢复使用原始查询?

预先感谢您的任何帮助。

您可以使用Compoships软件包:

class Vehicle extends Model
{
    use \Awobaz\Compoships\Compoships;

    public function policy()
    {
        return $this->hasMany(Policy::class, ['Group', 'Reference'], ['Group', 'Reference']);
    }
}

我假设查询已经作为原始SQL存在,而您想要实现的是将其转换为雄辩的。 如果是这种情况,您可能会发现使用内置的原始查询会更快一些。

暂无
暂无

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

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