我有两个模型作为Project和Collaborator,这是我的表
项目列id
project_name
project_note
user_id
合作者模型
id
project_id
collaborator_id
我需要加入这个模型来获得project_name而不是合作者模型的project_id。
我怎么能做到这一点。我读www.laravel.com文件,但很难理解。帮我写代码…
project Model
<?php
namespace App;
use Auth;
use Illuminate'Database'Eloquent'Model;
class Project extends Model
{
/*
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['project_name', 'project_notes', 'project_status', 'due_date'];
public function scopePersonal($query)
{
return $query->where('user_id', Auth::user()->id);
}
//
}
collaborator Model
<?php
namespace App;
use Auth;
use Illuminate'Database'Eloquent'Model;
class Collaboration extends Model
{
protected $table = 'project_collaborator';
/*
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['project_id', 'collaborator_id'];
/*
* Get the user that is a collaborator on another project
* @return collection
*/
public function user()
{
return $this->belongsTo(User::class, 'collaborator_id');
}
/*
* Query scope to return information about the current project
* @param $query
* @param int $id
* @return query
*/
public function scopeProject($query, $id)
{
return $query->where('project_id', $id);
}
public function scopeColabo($query)
{
return $query->where('collaborator_id',Auth::user()->id);
}
}
根据您的评论,您需要向您的协作模型添加一个关系hasOne:
class Collaboration extends Model
{
.....
public function project()
{
return $this->hasOne('App'Project');
}
.....
}
方法project()
将定义您与项目模型的关系。然后,您将能够获得像这样的协作项目名称:
$collaborations = Collaboration::with('project')->get();
foreach ( $collaborations as $collaboration ) {
echo $collaboration->project->project_name;
}
您可以在文档中阅读更多内容
在您的Collaboration
类中添加以下关系:
public function project()
{
return $this->belongsTo('App'Project');
}
在你的User
类中定义一个关系:
public function collaborations()
{
return $this->hasMany('App'Collaboration', 'collaborator_id');
}
然后你可以通过:
得到所有登录用户的协作$collaborations = auth()->user()->collaborations()->with('project')->get()
或
要获得所有合作,您可以这样做:
$collaborations = Collaboration::with('project')->get();
在你的视图文件中:
@foreach ($collaborations as $collaboration)
{{ $collaboration->project->project_name }}
@endforeach