如何取出with()带出的字段值?

代码如下:

$relation = Relation::where('mid',$id)->with('members')->get();

dd($relation);

array:2 [▼
  0 => array:7 [▼
    "id" => 1
    "mid" => 1
    "rid" => 2
    "name" => "兄弟"
    "created_at" => "2017-01-12 00:10:45"
    "updated_at" => "2017-01-12 00:10:45"
    "members" => array:1 [▼
      0 => array:12 [▼
        "id" => 2
        "name" => "张三"
        "avatar" => "images/avatar/default.png"
        "mobnumber" => "13800138000"
        "address" => "XXX省XXX市XX县"
        "created_at" => "2017-01-09 01:38:20"
        "updated_at" => "2017-01-09 01:38:23"
        "streaming" => "F"
        "pivot" => array:2 [▶]
      ]
    ]
  ]
  1 => array:7 [▼
    "id" => 3
    "mid" => 1
    "rid" => 10
    "name" => "表兄弟"
    "created_at" => "2017-01-12 00:22:20"
    "updated_at" => "2017-01-12 00:22:20"
    "members" => array:1 [▼
      0 => array:12 [▼
        "id" => 10
        "name" => "李四"
        "avatar" => "images/avatar/20170109090138-wXCL2.png"
        "mobnumber" => "13800138000"
        "address" => "XXX省XXX市"
        "created_at" => "2017-01-09 09:26:38"
        "updated_at" => "2017-01-09 09:26:38"
        "streaming" => "F"
        "pivot" => array:2 [▶]
      ]
    ]
  ]
]

可以看到所有的数据,我想在blade模板里调用第一级的name和members里的name字段,

@foreach($relation as $r)
    <p> $r->name : $r->members->name </p>
 @endforeach

怎么会提示错误呢?
我想显示为

兄弟:张三
表兄弟:李四

JellyBool
@foreach($relation as $r)
    <p>{{$r->name}}:{{$r->members()->first()->name}}</p>
 @endforeach

这样试试

John Howard 回复 @JellyBool

这样可以,真是太囧了!谢谢

lvqingan

$r->members()->pluck('name')->implode(', ')

JellyBool 微信公众号

不定期送书,送键盘,送订阅优惠