Laravel,获取关系数据

时间:2019-05-22 17:05:40

标签: laravel

我对Laravel中的关系有点陌生。

当我dd处理一个对象时,我得到了:

Collection {#485 ▼
  #items: array:1 [▼
    0 => Menu {#484 ▼
      #table: "menus"
      #fillable: array:6 []
      #hidden: array:2 [▶]
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:9 []
      #original: array:11 []
      #relations: array:2 [▼
        "pivot" => Pivot {#486 ▶}
        "subMenus" => Collection {#items: array:3 [▼
        0 => SubMenu {#488 ▼
          #table: "sub_menus"
          #fillable: array:5 []
          #hidden: array:2 []
          #connection: null
          #primaryKey: "id"
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:8 []
          #original: array:10 [▼
            "id" => 16
            "name" => "My name"   <--------- this is what I need to get
            "created_at" => "2018-11-20 15:19:14"
            "updated_at" => "2018-11-20 20:29:34"

如何从与我的dd(model)有关系的模型name中获取SubMenu的值?

Menu中,我有了恋爱关系:

public function subMenus()
{
    return $this->belongsToMany('App\SubMenu', 'menu_submenu', 'menu_id', 'submenu_id')->where('estado', Define::ESTADO_ACTIVO)->orderBy('orden');
}

我尝试过类似的事情:

dd($MyMenuObject->subMenus());

但不起作用。尝试使用get(),->子菜单等。

编辑:这是我的数据

有了dd($perfil_activo->menus);,我得到:

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以通过

访问它
$model->subMenus()->first()->name;

但是,由于$subMenus()是多对多关系,因此您可能应该通过循环来做到这一点:

foreach($model->subMenus AS $subMenu){
   $subMenu->name; // Do with as you please.
}

编辑:由于$model也是Collection,因此您需要使用->first()或循环:

$model->first()->subMenus->first()->name;

// OR

foreach($model AS $model){
   $model->subMenus->first()->name;
   // OR
   foreach($model->subMenus AS $subMenu){
       $subMenu->name;
   }
}

这全部取决于您如何获取$model;如果您的查询以->get()->all()结尾,它将为Collection。如果以->first()->find()等结尾,它将是单个Model

答案 1 :(得分:1)

您可以在数组:或对象上列出所有子菜单名称

$names=$model->subMenus()->pluck('name'); //object
//or
$names=$model->subMenus()->pluck('name')->toArray();// to array
dd($names);