简体   繁体   English

Laravel雄辩的HasMany / HasOne附加条款

[英]Laravel Eloquent HasMany / HasOne Additional On Clauses

Good morning, 早上好,

Apologies if this has been ask before but we are unable to find any answer to an issue we are having. 道歉,如果以前曾有人问过这个问题,但我们无法找到所遇到问题的任何答案。

We are working with a legacy database that is not owned by us (read-only) and are attempting to use Eloquent (Models) in Laravel to solve some common issues. 我们正在使用一个不属于我们的旧数据库(只读),并且正在尝试使用Laravel中的Eloquent(模型)来解决一些常见问题。

Is it possible to setup Eloquent's Eager-loading to create additional ON clauses to the HasMany / HasOne relationship builder? 是否可以设置Eloquent的Eager-loading来为HasMany / HasOne关系构建器创建其他ON子句?

Please see below of what we are trying to achieve without raw queries. 请在下面看到我们在没有原始查询的情况下要实现的目标。

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

In our controller we have attempted the following which also fails. 在我们的控制器中,我们尝试了以下操作,但也失败了。

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

Can the above be achieved or do we have to revert back to using raw queries? 可以实现上述目标吗?还是必须恢复使用原始查询?

Thank you in advance for any help. 预先感谢您的任何帮助。

You can use the Compoships package: 您可以使用Compoships软件包:

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

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

I am assuming the query already exists as raw SQL and what you are trying to achieve is to convert it to using eloquent. 我假设查询已经作为原始SQL存在,而您想要实现的是将其转换为雄辩的。 If that is the case you may find it quicker an deasier to use the built in raw query. 如果是这种情况,您可能会发现使用内置的原始查询会更快一些。

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

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