我在laravel的2个桌子之间有很多关系。
我只想用user_id = 45来获取afdeling的名称。
我试过
$afdelingen = User::find(45)->afdelingen->pluck('name');
但是不起作用。它的工作没有采摘,但后来我得到一个长串:
[{"id":3,"afdelingen":"Personeelszaken","user_id":0,"pivot":{"user_id":45,"afdeling_id":3}}]
我怎么才能得到
模型1代码:
<?php
class Afdeling extends Eloquent {
protected $guarded = array();
public static $rules = array();
protected $connection = 'mysql2';
protected $table = 'afdelingen';
public function users(){
return $this->belongstoMany('User','afdeling_user','afdeling_id');
}
}
模型2代码:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $connection = 'mysql2';
protected $table = 'users';
//public function safetyreports(){
// return $this->hasMany('Safetyreport');
//}
public function afdelingen(){
return $this->belongstoMany('Afdeling','afdeling_user','user_id');
}
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
答案 0 :(得分:2)
由于它是多对多的关系,$afdelingen = User::find(45)->afdelingen->pluck('name');
会有afdelingen
的集合,而不只是一个。
您可以使用$afdelingen = User::find(45)->afdelingen()->first()->pluck('name');
此外,您可以循环获取所有名称。
foreach(User::find(45)->afdelingen as $item) {
$afdelingen = $item->pluck('name');
}
或者如果你想要一个名字数组......
$afdelingen = User::find(45)->afdelingen()->lists('name');