从同一模型中将变量传递给laravel方法

时间:2017-11-22 15:27:40

标签: php laravel laravel-5

我正在为Laravel应用程序进行一些多租户更新,但在尝试将特定团队ID传递到另一个方法中的模型上的方法时遇到问题。

示例:

在控制器中:

$waitTime = $booking->estimatedWaitTime($teamId);

在预订模式中:

public function queueLength()
{
    $booking = $this->todaysBookings;

    foreach ($bookings as $booking) {
        // Calculate the length of all bookings
    }
}

public function todaysBookings()
{
    return $this->hasMany('App\UserBooking')->whereHas('booking', function ($q) {
        $q->where('team_id', 2);
    });
}

这正确地返回预订并允许我在queueLength方法中循环它们。但是,我希望能够将team_id传递给todaysBooking方法。

而是将todaysBookings称为方法:

$booking = $this->todaysBookings();

它没有任何东西让我循环。

如何实现我想在这里做的事情?

1 个答案:

答案 0 :(得分:1)

您可以将id作为参数传递,然后获得结果:

public function todaysBookings($team_id)
{
    return $this->hasMany('App\UserBooking')->whereHas('booking', function ($q) use($team_id) {
        $q->where('team_id', $team_id);
    });
}

在通话中,您可以执行以下操作:

$some_teame_id = 2;
$booking = $this->todaysBookings($some_teame_id)->get();

为什么?

因为laravel中的关系充当强大的查询构建器(documentation):

  

Eloquent关系被定义为您的Eloquent模型上的方法   类。因为,就像Eloquent模特本身一样,关系也是如此   充当强大的查询构建器,将关系定义为方法   提供强大的方法链接和查询功能。

Relationship Methods Vs. Dynamic Properties

当您想要添加更多条件和过滤器时,需要调用关系作为方法:

$booking->todaysBookings()->where('active', 1)->get(); //just an example :)

如果您不需要为Eloquent关系查询添加其他约束,您可以简单地访问该关系,就像它是属性一样, Laravel会为您添加get():)< / EM>

$booking->todaysBookings