简体   繁体   中英

how to get all rows where specific column = id of other row in different table

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 😀

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM