【发布时间】:2019-09-09 16:02:32
【问题描述】:
我有一个名为“registrations”的数据库表,它将用户映射到他们在给定项目中扮演的角色。例如,用户可以是项目 A 中的项目负责人,也可以是项目 B 中的常规项目工作人员或项目 C 中的主管。因此,“registrations”表有两个外键,一个将其连接到“users”表,另一个将其连接到“users”表。另一个到“项目”表。我创建了一个视图,我想在其中列出特定用户的所有项目参与。但是,我一直在使用 Laravel 集合、数组和对象,因为我不知道如何为视图提供它需要的集合,以便它可以循环显示当前用户的所有项目一部分。 使用下面的代码时,我只将最后一个项目移交给视图(即通过 foreach 循环的最后一个项目)。但是,如前所述,我要求列出他的所有项目。
我尝试在控制器的 foreach 循环中为 $projects 创建一个数组,但这基本上将集合包装到另一个数组外壳中。添加 ->toArray() 时,它会生成一个简单的数组,但我无法访问视图中的属性,因为它不是对象。也许有人可以指出我正确的方向。
以下是模型:
registration.php
<?php
namespace konsens24;
use Illuminate\Database\Eloquent\Model;
class Registration extends Model
{
...
public function user()
{
return $this->belongsTo(User::class);
}
public function project()
{
return $this->belongsTo(Project::class);
}
}
用户.php
<?php
namespace konsens24;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
...
public function projects()
{
return $this->hasMany(Project::class, 'owner_id');
}
...
public function registrations()
{
return $this->hasMany(Registration::class, 'user_id');
}
}
项目.php
<?php
namespace konsens24;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
...
public function owner()
{
return $this->belongsTo(User::class);
}
public function registrations()
{
return $this->hasMany(Registration::class, 'project_id');
}
...
}
ProjectsController.php
<?php
namespace konsens24\Http\Controllers;
use Illuminate\Http\Request;
use konsens24\Project;
use konsens24\Mail\ProjectCreated;
use konsens24\User;
use konsens24\Registration;
use Illuminate\Support\Facades\DB;
class ProjectsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$registrations = auth()->user()->registrations;
foreach ($registrations as $registration) {
$project_id = $registration->project_id;
$projects = Project::where('id', $project_id)->get();
foreach ($projects as $project){
echo $project->id; // just for testing purposes, it displays the correct info here
echo $project->title; // just for testing purposes, it displays the correct info here
}
}
return view('projects.index', compact('registrations', 'projects'));
}
...
}
index.blade.php
@extends('layouts.app')
@section('content')
<h1 class="title">Cases</h1>
<ul>
@foreach ($projects as $project)
<li>
<a href="/projects/{{ $project->id }}">
{{ $project->title }}
</a>
</li>
@endforeach
</ul>
@endsection
【问题讨论】:
标签: laravel laravel-5 eloquent