Laravel 3 Table 关系

Laravel 3 Table Relationship

谁能帮我看看如何显示产品名称?我的购买记录中存储了产品数量,现在我想在产品数量记录中显示产品名称。

我有 3 张桌子

购买记录

产品数量

产品

控制器:

public function createpurchase(Request $request)
{
        $purchasenumber = $request->purchasenumber;
        $dataPurchaseRecord = Purchaserecord::where('purchasenumber','=',$purchasenumber)->with('productquantity')->get();
        return view('admin.createpurchase',compact('purchasenumber', 'dataPurchaseRecord')); 

}

查看:

@forelse($dataPurchaseRecord as $Request)
              <tr>
                <td> <a class="name">{{$Request->productquantity->prod_id}}</a></td>
                <td><em class="productprice">{{$Request->quantity}}</em>  </td>
                <td style="width:100px;" class="td-actions"><a href="javascript:;" class="delete-modal btn btn-mini btn-danger" data-id="{{$Request->id}}" ><i class="icon-minus"> </i>Remove</a> </td>
               </tr>
               @empty
               <tr><td colspan='4'><em>No Data</em></td></tr>
              @endforelse

型号:

 public function product()
{
    return $this->belongsTO('App\Product', 'prodquantityid', 'id');
}

{{$Request->productquantity->prod_id}} 应该显示产品名称而不是 id 我如何构建模型并对此进行查看?

您可以将模型定义为

Class Purchaserecord extends Model{

    public function productquantity()
    {
        return $this->belongsTo('App\Productquantities', 'prodquantityid');
    }
}

Class Productquantities extends Model{

    public function product()
    {
        return $this->belongsTo('App\Product', 'prod_id');
    }

    public function purchaserecords()
    {
        return $this->hasMany('App\Productquantities','prod_id');
    }
}

Class Product extends Model{

    public function productquantities()
    {
        return $this->hasMany('App\Productquantities','prod_id');
    }
}

现在像

一样急切加载您的数据
$dataPurchaseRecord = Purchaserecord::where('purchasenumber','=',$purchasenumber)
                                    ->with('productquantity.product')
                                    ->get();

在循环中,您以 $Request->productquantity->product->name

访问产品对象

Eloquent: Relationships