繁体   English   中英

在Laravel中使用视图参数调用模型函数

[英]Call model function with parameter from view in Laravel

我有两个处于一对多关系的模型

Tour.php

class Tour extends Model{
protected $table = 'tours';

  public function datePrice()
  {
    return $this->hasMany('App\DatePrice', 'tour_id')->orderBy('start', 'asc');
  }    
}

DatePrice.php

class DatePrice extends Model
{
 public $timestamps = false;
 protected $table = 'dateprice';
 protected $fillable = [
'tour_id',
'start_day',
'start_month',
'start_year',
'end_day',
'end_month',
'end_year',
'price'];
 public function tour() 
 {
    return $this->belongsTo('App\Tour', 'tour_id');
 }

 public function scopeFixedDates($query, $date)
 {
    return $query->where('start_year', '=' , $date);
 }
}

我试图根据传递给我的tour.show route和view模型函数的参数的年份来获取旅行日期。 我在show.blade.php视图中获取数据的代码是:

@foreach($tour->datePrice()->FixedDates(date('Y')) as $date)
<tr>
<td>
{{ date("jS M, Y", strtotime($date->start_month.'/'.$date->start_day.'/'.$date->start_year )) }}
</td>
<td>
    {{ date("jS M, Y", strtotime($date->end_month.'/'.$date->end_day.'/'.$date->end_year )) }}
</td>
</tr>
@endforeach

上面的代码给我带来的麻烦是没有抛出任何错误消息或没有给我结果。 我有1行充满了2017年的开始年份。该表应该充满数据,但是它是空的。 当我在foreach循环中转储{{$date}}并使其死掉时,结果是空白页。如果有人能指出我正在犯的错误或建议的其他替代输出方式,我将不胜感激。

您不能以这种方式访问​​关系:

$tour->datePrice()

相反,您使用magic属性:

$tour->date_price

我认为最好在不同情况下使用范围:

$tour->date_price->fixedDates(date('Y')

@foreach($tour->datePrice()->FixedDates(date('Y'))->get() as $date)

但不要在视图模板中执行此操作,首先在控制器中准备数据并将其传递给视图:

// controller
view(..)->with(['dates' => $tour->datePrice()->FixedDates(date('Y'))->get()]);

// view
@foreach($dates as $date)

您的代码之所以可以正常工作,是因为您将Eloquent\\Builder类传递给了foreach,因此,它是该构造的有效参数,但显然并不能满足您的期望/期望。

暂无
暂无

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

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