【问题标题】:many-to-many relationschop in laravel eloquent does not work with pluck()laravel eloquent 中的多对多关系对 pluck() 不起作用
【发布时间】: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


    【解决方案1】:

    由于它是多对多关系,$afdelingen = User::find(45)-&gt;afdelingen-&gt;pluck('name'); 将拥有 afdelingen 的集合,而不仅仅是一个。

    你可以通过$afdelingen = User::find(45)-&gt;afdelingen()-&gt;first()-&gt;pluck('name');获得第一个

    此外,您可以循环获取他们所有的名字。

    foreach(User::find(45)->afdelingen as $item) {
        $afdelingen = $item->pluck('name');
    }
    

    或者如果你想要一个名称数组...

    $afdelingen = User::find(45)-&gt;afdelingen()-&gt;lists('name');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 2021-12-08
      • 2019-03-26
      • 2013-05-15
      • 2014-09-27
      • 1970-01-01
      相关资源
      最近更新 更多