user0129e021939232
user0129e021939232

Reputation: 6355

laravel eloquent repository query foreign key tables

hi i am using a custom repository and I am getting comfortable with querying one table to retrieve data like so:

public function getAll()
{
// get all logged in users projects order by project name asc and paginate 9 per page
return \Auth::user()->projects()->orderBy('project_name', 'ASC')->paginate(9);

}

and in my controller I simply call

public function __construct(ProjectRepositoryInterface $project) {

    $this->project = $project;

}

public function index()
    {
        $projects = $this->project->getAll();
        echo View::make('projects.index', compact('projects'));         
    }

and my view is as so:

@if (Auth::check())
 @if (count($projects) > 0)
@foreach ($projects as $project)
{{ $project->project_name }}
 @endforeach 
 @else
  <p>No records, would you like to create some...</p>
@endif
 {{ $projects->links; }}
 @endif

However within my projects table I have a status_id and a client_id and I want to retrieve records of this these tables with the logged in user but I am not sure how to structure my query, does anyone have any guidance?

Upvotes: 0

Views: 1936

Answers (1)

bryant
bryant

Reputation: 2051

According to the laravel documentation, In your project model you can add the following function:

class Project extends Eloquent
{
    public function clients()
    {
        return $this->hasMany(Client::class);
    }
}

In your client model you can then add the inverse of the relationship with the function:

class Client extends Eloquent
{
    public function project()
    {
        return $this->belongsTo(Project::class);
    }
}

Then you can retrieve the data with a function like:

$clients = Project::find(1)->clients;

Upvotes: 1

Related Questions