【问题标题】:Create a nested JSON object with two laravel eloquent model objects使用两个 laravel eloquent 模型对象创建一个嵌套的 JSON 对象
【发布时间】:2020-04-07 11:38:19
【问题描述】:

我是 Laravel 的新手,现在我正在使用 Laravel Broadcast 的项目中加入实时通知 UI(类似于通知提醒下拉菜单)。我想从我正在使用的 api 中模仿 JSON 格式,一旦从我的日志(约会)中触发事件,就会被抛出,这样一旦扔到前端就更容易操作。我想模仿的对象与下面的类似。

[
{
    "id": 39,
    "user_id": 1,
    "campaign_id": 134,
    "lead_id": 12785,
    "date": "2020-04-16 08:43:00",
    "type": "phone-appointment",
    "created_at": "2020-04-05 08:43:38",
    "updated_at": "2020-04-05 08:43:38",
    "lead": {
        "id": 12785,
        "first_name": "First Name",
        "last_name": "Last Name",
        "phone_number": "+12345678911",
        "city": null,
        "car": null,
        "created_at": "2020-02-11 21:33:19",
        "updated_at": "2020-02-11 21:33:19"
    }
]

我使用的是多态关系,api是用这个代码索引的:

public function index()
{
    $userIsSuperAdmin = $this->user->role->contains('name', 'super-admin');
    $userIsManager = $this->user->role->contains('name', 'manager');

    $notifications = Notification::whereNull('read_at')
        ->where(function ($query) use ($userIsSuperAdmin, $userIsManager) {
            if ($userIsSuperAdmin) {
                return true;
            }

            if ($userIsManager) {
                return $query->whereIn('user_id', $this->user->company->users->pluck('id'));
            }

            return $query->where('user_id', $this->user->id);
        })
        ->orderBy('created_at', 'desc')
        ->get();

    $result = [];

    foreach ($notifications as $notification) {

        switch ($notification->notificationable_type) {
            case 'appointment';
                $origin = CampaignLeadAppointment::with('lead')
                    ->where('id', $notification->notificationable_id)
                    ->first();

                $result[] = $origin;
                break;
            case 'sms';
                $origin = IncomingSms::with('lead')
                    ->where('id', $notification->notificationable_id)
                    ->first();
                $result[] = $origin;
                break;
            case 'call';
                $origin = IncomingCall::with('lead')
                    ->where('id', $notification->notificationable_id)
                    ->first();
                $result[] = $origin;
                break;
        }
    }

   return $result;

}

我制作的事件广播控制器在创建新日志时触发:

class NewNotification implements ShouldBroadcast

public $notification;

/**
 * Create a new event instance.
 *
 * @param $notification
 */

public function __construct($notification)
{
    $this->notification = $notification;
}

/**
 * Get the channels the event should broadcast on.
 *
 * @return \Illuminate\Broadcasting\Channel|array
 */
public function broadcastOn()
{
    return new Channel('new-notification');
}

public function broadcastWith()
{
    if ($this->notification->lead_id != 0) {

        $lead = Lead::where('id', $this->notification->lead_id)->first();

        return array_merge($this->notification->toArray(), $lead->toArray());
    }

    return $this->notification->toArray();

}

这是它向 vue 前端监听器抛出的数据(错误的 JSON):

[
{
    "id": 13521,
    "user_id": 1,
    "campaign_id": 134,
    "date": "2020-04-16 08:43:00",
    "type": "phone-appointment",
    "created_at": "2020-04-05 08:43:38",
    "updated_at": "2020-04-05 08:43:38",
    "lead_id": 13521,
    "first_name": "First Name",
    "last_name": "Last Name",
    "phone_number": "+12345678911",
    "city": null,
    "car": null,
    }
]

我正在尝试使用 json_encode,但它所做的只是将通知对象和引导对象分开,而不是将其嵌套在其中。我应该使用什么语法,以便我可以将一个 eloquent 模型对象嵌套到另一个 eloquent 模型对象而不使用 with方法?

【问题讨论】:

  • 您好,您能发布一个错误 json 的示例吗?据我现在所知,您可能需要以相同的方式加载通知,然后再将其作为事件/通知抛出,如下所示:$notification = Notification::with('lead')->find($id); event(new NewNotification($notification));
  • @RobBiermann 添加了错误的 json。我无法像那样加载它,因为我使用多态关系从 3 个不同的日志表中获取通知表。不能从事件/通知端操作数据吗?
  • 我已经测试过了,我认为解决方案可以相当简单:在你发出事件并在那里传递 $notification 之前,你应该能够调用 $notification->lead,有效地加载线索数据,并使其在模型中可用。
  • 我正在使用多态关系从 3 个不同的日志表中获取通知表:我不知道为什么这是不可能的,你能详细说明你到目前为止尝试了什么吗?
  • 我无法直接从 $notification 调用潜在客户,因为它们之间没有直接关系。通知控制器的结构隐藏在 api 中,只有实际看到的是约会日志本身和潜在客户。 Notification 与 IncomingSMS、IncomingCall 和 Appointments 具有多态关系。而约会模式属于潜在客户。我只能通过约会类而不是直接从通知本身调用潜在客户。

标签: php json laravel


【解决方案1】:

使用它而不是 array_merge() 似乎已经回答了这个问题。

 public function broadcastWith()
{
    if ($this->notification->lead_id != 0) {

        $lead = Lead::where('id', $this->notification->lead_id)->first();

        $arr = $this->notification->toArray();
        $arr['lead'] = $lead->toArray();

        return $arr;
    }

    return $this->notification->toArray();

}

现在发送到前端的事件数据结构如下:

{
"id": 39,
"user_id": 1,
"campaign_id": 134,
"lead_id": 12785,
"date": "2020-04-16 08:43:00",
"type": "phone-appointment",
"created_at": "2020-04-05 08:43:38",
"updated_at": "2020-04-05 08:43:38",
"lead": {
    "id": 12785,
    "first_name": "First Name",
    "last_name": "Last Name",
    "phone_number": "+12345678911",
    "city": null,
    "car": null,
    "created_at": "2020-02-11 21:33:19",
    "updated_at": "2020-02-11 21:33:19"
}

How to add element to JSON object using PHP?

【讨论】:

  • 或者更简单地说,我刚刚了解到您可以通过简单地使用 $lead = $this->notification->lead 将线索附加到通知中。它抛出了与上面类似的结构。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 2018-07-18
  • 2016-10-16
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多