$class = json_decode (Class::with(array('members'))->where('id', 1)->get());
我打电话给$class->name;
试图获取非对象的属性
var_dump($class)
得到了
array(1) { [0]=> object(stdClass)#305 (12)
{ ["id"]=> string(1) "1"
["name"]=> string(15) "chemistry"
["days"]=> string(2) "30"
["started_at"]=> string(10) "2015-02-15"
["complete_at"]=> string(10) "0000-00-00"
["completed"]=> string(1) "0"
["created_at"]=> string(19) "2015-03-20 10:27:02"
["updated_at"]=> string(19) "2015-03-20 10:27:02"
["deleted_at"]=> NULL
["members"]=> array(8)
{
[0]=> object(stdClass)#289 (3) { ["id"]=> string(1) "1" ["name"]=> string(6) "John" ["pivot"]=> object(stdClass)#306 (2) { ["class_id"]=> string(1) "1" ["member_id"]=> string(1) "1" } }
[1]=> object(stdClass)#326 (3) { ["id"]=> string(1) "2" ["name"]=> string(5) "Elly" ["pivot"]=> object(stdClass)#322 (2) { ["class_id"]=> string(1) "1" ["member_id"]=> string(1) "2" } }
[2]=> object(stdClass)#325 (3) { ["id"]=> string(1) "3" ["name"]=> string(8) "Chris" ["pivot"]=> object(stdClass)#324 (2) { ["class_id"]=> string(1) "1" ["member_id"]=> string(1) "3" } } } } }
下面还获取尝试获取非对象的属性
foreach($class->members as $member){
var_dump($member->name);
}
我建议不要使用 ->get((,而是使用 ->first((,因为您正在尝试获取单个记录。
$class = Class::with(array('members'))->where('id', 1)->first();
这将返回单个对象,而不是对象数组。
如果要获取多个模型,可以通过类使用 get 然后 foreach,然后在类的 foreach 中,可以通过单个类的成员进行 foreach。
示例:(单条记录(
$class = Class::with(array('members'))->where('id', 1)->first();
foreach($class->members as $member)
{
echo '<pre>';
var_dump($member);
}
示例 #2:(多个结果(如果要获取多个类(假设您没有将查询限制为单个结果的 where 子句(。
$classes = Class::with(array('members'))->where('id', 1)->get();
foreach($classes as $class)
{
//Data for a single Class model from this collection:
foreach($class->members as $member) {
//Data for a single member for a single class
}
}