我正在尝试获取支付表中的所有行,其中我有另一个表称为项目我希望获取支付表中的所有行,其中project_id列=项目表中行的ID我正在使用Laravel框架请帮助我这个代码
付款模式
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payment extends Model
{
protected $table = 'payments';
public function projects() {
return $this->belongsTo('App\Project');
}
}
项目模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $table = "projects";
public function payments() {
return $this->hasMany('App\Payment');
}
}
路线档案
Route::get('special/{project_id}', 'SpecialController@index');
Controller中的索引函数
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Payment;
use Illuminate\Http\Request;
class SpecialController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Project $project_id)
{
return view('special.index')->with(['projects' => $project_id]);
}
这是我的问题请帮忙 一切顺利
答案 0 :(得分:3)
在你的控制器中,我看到你在Project中注入了一个实例,但命名为$ project_id。这不是id,id会被解析为Project的一个实例。
public function index(Project $project_id)
只是一张纸条。使用index方法显示列表,除非它是嵌套资源。
public function index(Project $project)
{
//assuming that $project is an instance of Project
$project = $project->with('payments')->get();
//$project will now include the related payments as well
//if you want to check do this, for debugging uncomment next line
//dd($project->toArray());
return view('special.index')->with(['project' => $project]);
}
代码中发生的事情是$项目是通过其相关付款来检索的。在with('payments')
付款&#39;是这种关系的名称。