Laravel5中的一对多关系无法正常工作

时间:2015-11-09 07:29:38

标签: php laravel laravel-5.1

我有一个收集控制器

看起来像这样

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Middleware\Role;
use Illuminate\Support\Facades\Input;
use App\User;
use App\Invoice;
use Session;
use Validator;


class CollectionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */

  public function __construct(){

    $this->middleware('role:collector'); // replace 'collector' with whatever role you need.
}
   public function getPayment($invoiceid){


         $id =$invoiceid;
         $invoice=Invoice::where('Id', $id)->with(['payments'])->get();


         return View('collectionmodule/payment')->with(array('invoice'=>$invoice));

 }

}

然后我有以下模特 的发票

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    //
     protected $table = 'event_invoice';

     public function payments(){
        return $this->hasMany('App\paymentrecieved','invoice_id');
    }

    public function comments(){
        return $this->hasMany('App\comments','invoice_id');
    }
}

Paymentrecieved

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class paymentrecieved extends Model
{
    //
    protected $table = 'paymentrecieved';

    public function invoice(){

            return $this->belongsTo('App\Invoice');

        }


}

因此,对于每个发票,可能会有多笔付款。

所以在我的getPayment方法中,我正在写这样的查询。

$invoice=Invoice::where('Id', $id)->with(['payments'])->get();

它从发票表中获取详细信息。但它没有给我任何付款细节

任何人都知道为什么会这样,据我说我已经正确地完成了这段关系

谢谢

1 个答案:

答案 0 :(得分:1)

您使用Id(大写)作为主键,但Invoice模型正在查找id(小写)。

您应该在Invoice模型中定义主键,如下所示:

protected $primaryKey = 'Id';