Laravel模型就像阵列一样?

时间:2018-02-25 07:48:14

标签: php laravel laravel-5.5

我知道PHP数组对象,但我从未见过像这样工作的laravel模型...它有点奇怪。这是实际的代码..

 public function getUserChats()
{
    $users = [];
    $chats1 = Chat::where('sender_id','=',auth()->user()->id)->get();
    $chats2 = Chat::where('reciever_id','=',auth()->user()->id)->get();
    foreach ($chats2->toArray() as $chat2) {
        $user = new UserResource(User::where('id','=',$chat2['sender_id'])->first());
        array_push($users, $user);
    }
    foreach ($chats1->toArray() as $chat1) {
        $user = new UserResource(User::where('id','=',$chat1['reciever_id'])->first());
        array_push($users, $user);
    }
    return $users;
}


//The above method works but this one doesn't works
 public function getUserChats()
{
    $users = [];
    $chats1 = Chat::where('sender_id','=',auth()->user()->id)->get();
    $chats2 = Chat::where('reciever_id','=',auth()->user()->id)->get();
    foreach ($chats2->toArray() as $chat2) {
        $user = new UserResource(User::where('id','=',$chat2->sender_id)->first());
        array_push($users, $user);
    }
    foreach ($chats1->toArray() as $chat1) {
        $user = new UserResource(User::where('id','=',$chat1->reciever_id)->first());
        array_push($users, $user);
    }
    return $users;
}

请注意每个循环内部我如何从$ chat1和$ chat2访问sender_id。我想知道它们究竟发生了什么......更多的是理论上的 问题...感谢您的回复

1 个答案:

答案 0 :(得分:4)

当您使用get()方法,you're getting a collection of objects而不仅仅是一个对象时,您可以遍历该集合。

当您使用$model['property']语法时,它可以正常工作,因为Model类实现了ArrayAccess接口。 Laravel使用offsetGet()方法返回对象属性。

此外,您不需要使用->toArray()方法。您可以迭代一个集合,因为Collection类实现了IteratorAggregate