简体   繁体   English

Laravel 5如何在使用Blade模板的视图中调用函数时使用参数

[英]Laravel 5 How to use parameters when calling a function in a view using Blade Template

I have a foreach in my view which displays tasks. 我的视图中有一个foreach,可显示任务。

 @foreach($project_item->getVisibleTasks($tasklist->id) as $task)

And in my model I have the following function: 在我的模型中,我具有以下功能:

  public function getVisibleTasks($tasklist_id)
  {
    return $this->hasMany('App\Task', 'project_id')->where('tasklist_id', $tasklist_id)->orderBy('order', 'asc');
  }

The function does work when I delete the parameters. 删除参数后,该功能确实起作用。 (But shows all the results. Because the where clause is deleted). (但是显示所有结果。因为where子句已删除)。 When I pass a static number (for example 1) in my view, it still doesnt work. 当我在视图中传递一个静态数字(例如1)时,它仍然不起作用。

How can I make this work? 我该如何进行这项工作?

Regards, 问候,

Dylan 迪伦

I'm not sure you can use a where clause when setting an eloquent relationship. 我不确定在设置雄辩的关系时是否可以使用where子句。 The Laravel Eloquent Relationship doc page doesn't say that is possible. Laravel雄辩的关系doc页面说这是不可能的。

If possible use the code below where you rather use the eloquent query builder; 如果可能,请使用下面的代码,而不要使用精巧的查询生成器;

public function getVisibleTasks($tasklist_id){
    return App\Task::where('id',$this->project_id)->where('tasklist_id',$tasklist_id)->orderBy('order', 'asc')->get();
}

it may not be working because the relationship query is being called inside the relationship, you could create a relationship function and a query function, for example 它可能不起作用,因为在关系内部调用了关系查询,您可以创建一个关系函数和一个查询函数,例如

public functon tasks() {
    return $this->hasMany('App\Task', 'project_id');
}

and then your function will be like this 然后你的功能会像这样

public function getVisibleTasks($tasklist_id)
  {
    return $this->tasks()->where('tasklist_id', $tasklist_id)->orderBy('order', 'asc');
  }

that way laravel fetch the relationship and then filter it. laravel通过这种方式获取关系,然后对其进行过滤。

See this post 看到这个帖子

This seems odd to me, it looks as though you are defining a relationship and running the query where the relationship is defined. 这对我来说似乎很奇怪,似乎您正在定义一个关系并在定义该关系的地方运行查询。 you should first define the relationship in the project_item model 您应该首先在project_item模型中定义关系

 public function getVisibleTasks()
      {
        return $this->hasMany('App\Task', 'project_id');
      }

Also define the inverse of that relationship. 还定义该关系的逆关系。

Then call it from your controller via 然后通过控制器从其调用

$project_item ->getVisibleTasks()->orderBy('order', 'asc'); this will automatically call the data that is related to your model. 这将自动调用与您的模型相关的数据。

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

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