gpt4 book ai didi

php - Laravel 关系

转载 作者:行者123 更新时间:2023-11-29 04:37:13 24 4
gpt4 key购买 nike

我有一个基本的应用程序,它将费用存储在一个包含以下列的表中:

  • id
  • user_id
  • quote_id(可为空)
  • 标题
  • 类型
  • 网络

quote_id 列链接到我的 quotes 表;但是,表中也可以有没有 quote_id 的条目。

我试图通过在我的 user 模型上使用关系 expenses() 来输出所有费用。

@foreach(Auth::user()->expenses as $e)
{{ $e->id }}
{{ $e->net }}
{{ $e->quote->title }}
{{ $e->quote_id }}
@endforeach

在我的 expenses 模型中,我还在 expensequote 之间建立了关系。

public function quote()
{
return $this->hasMany('App\Quote', 'id','quote_id');
}

当表格中始终有 quote_id 但有些条目没有 quote_id 并且我收到以下错误时,这非常有用:

Undefined property: Illuminate\Database\Eloquent\Collection::$title

我该如何解决?

最佳答案

据我所知(从您的数据库结构),每个 expense 只有一个 quote 并不多。换句话说,首要任务是将您的 $expense->quote() 函数更改为:

public function quote()
{
return $this->hasOne('App\Quote', 'id', 'quote_id');

// Since your column naming is standard, this should work too:
// return $this->hasOne('App\Quote');
}

然后,由于 quote_id 可以是 null,您仍然需要检查 expensequote() 是一个对象。像这样的东西可以用在你的 Blade 模板中:

@if($e->quote)
{{ $e->quote->title }}
{{ $e->quote_id }}
@endif

如果您继续使用 hasMany() 而不是 hasOne()(无论出于何种原因),那么 quote() 将返回一个array 您可以循环访问的 quote 对象。

@foreach($e->quote as $q)
{{ $q->title }}
@endforeach

关于php - Laravel 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38446541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com