【问题标题】:Error with Eloquent one to many relationshipEloquent 一对多关系的错误
【发布时间】:2018-11-19 02:03:04
【问题描述】:

一对多模型存在问题。我知道要访问一个 1 到多个,需要迭代一个 foreach 循环。我这样做并得到空白。

物品模型

class Item extends Model

{
protected $table = 'items';
public function offers(){
    return $this->hasMany('App\Offer','listing_id');
}

报价模式

class Offer extends Model
{
    protected $table = 'offers';

    public function item(){
        return $this->belongsTo('App\Item','listing_id');
    }
}

物品控制器:

public function index()
{
    $user_id = auth()->user()->id;

    $listings = Item::with('offers')->where('user_id','1')->paginate(2);;
    return view('user.dashboard')->with('listings',$listings);
}

查看:

@foreach ($listings as $listing)
    {{listing->offer_price}}
@endforeach

所以我试图通过 {{listing->offer_price}} 从报价表中引用一个值,但视图中没有显示任何内容 - 空白?每个项目都有多个报价

【问题讨论】:

    标签: php sql laravel laravel-blade


    【解决方案1】:

    你需要两个循环:

    @foreach ($listings as $listing)
        @foreach ($listing->offers as $offer)
            {{ $offer->price }}
        @endforeach
    @endforeach
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 2021-10-09
      • 2021-04-21
      • 2017-04-20
      • 2019-06-13
      • 1970-01-01
      相关资源
      最近更新 更多