【发布时间】:2014-03-14 15:56:18
【问题描述】:
我在 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;
}
}
【问题讨论】:
标签: laravel many-to-many eloquent