douba9654 2017-10-01 17:30
浏览 62
已采纳

如何获取不同表中其他行的特定列= id的所有行

I am trying to get all rows in a payments table where I have another table called projects I want to get all rows that in payments table where project_id column = ID of the row inside projects table I am using Laravel framework please help me this some the code

Payment Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    protected $table = 'payments';

    public function projects() {
        return $this->belongsTo('App\Project');
    }
} 

Project Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    protected $table = "projects";

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

}

Route File

 Route::get('special/{project_id}', 'SpecialController@index');

The index function in the 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]);
    }

This is my problem please help
All the best

  • 写回答

1条回答 默认 最新

  • douzi1986 2017-10-01 18:03
    关注

    In your controller, I see that u have injected an instance if Project, but named as $project_id. Thats not an id, id would have been resolved to an instance of Project.

    public function index(Project $project_id)
    

    just a note. use index method to show the listing, unless its a nested resource.

    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]);
    }
    

    whats happening in code is that $project is retrieved with its related payments. in with('payments') the 'payments' is the name of the relationship.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?