如何基于保存在表列中的json数据键在Laravel 5.7中建立关系?

问题描述 投票:0回答:1

我在Laravel中使用此Staudenmein package,并指代包所有者自己给出的答案。

我有两个表,模型为petsnotificationsPetNotificationnotifications表具有名为data的列,该列具有JSON数据类型并存储JSON数据

{"pet_id":"4","pet_type_id":1,"lost_report_id":3,"pet_sighting_id":21,"latitude":"22.676846","longitude":"88.338509"}

pet_id表示id表的pets列。我需要一种关系,以便可以从pets表中获取宠物的名字。

通过参考上面给出的答案链接,我这样编写了Notification模型:-

namespace App\Models;

use DB, App, Auth, Hash, Lang, Mail, Config, Exception, Validator, Globals;
use Illuminate\Database\Eloquent\Model;

use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;

use App\User;
use App\Models\AdminConfig;
use App\Models\ReceivedAppNotification;

class Notification extends Model
{

    protected $casts = [
           'data' => 'json'
        ];

    public function notificationPet()
    {
        return $this->belongsTo('App\Models\Pet', 'data->pet_id');
    }
}

当我像这样运行查询时:-

$notificationQuery = Notification::with('notificationPet')
                             ->whereRaw("FIND_IN_SET('$userId', in_app_notification_receiver)")
                             ->where(array(
                                  'status'     => Globals::SMALL_CHAR_ACTIVE,
                                  'is_delete'  => Globals::SMALL_CHAR_NO,
                               ))->get()->toArray();

我将NotificationPet关系设为空,即数据集是这样的:-

Array
(
    [id] => 10
    [title] => 
    [message] => 
    [data] => Array
        (
            [pet_id] => 4
            [latitude] => 22.676846
            [longitude] => 88.338509
            [pet_type_id] => 1
            [lost_report_id] => 3
            [pet_sighting_id] => 34
        )

    [no_of_in_app_notification_receiver] => 2
    [no_of_push_notification_receiver] => 1
    [from_user] => 22
    [in_app_notification_receiver] => 2,23
    [push_notification_receiver] => 2
    [status] => a
    [is_delete] => n
    [push_notification_sent] => n
    [created_date] => 2020-03-19 13:23:17
    [modified_date] => 2020-03-19 13:23:17
    [created_at] => 2020-03-19 13:23:17
    [updated_at] => 2020-03-19 13:23:17
    [notification_pet] => 
)

但是,我已经在pets表中有一个ID为4的记录。因此,该关系不应为空。

我在做什么错?

json laravel relationship laravel-5.7 staudenmein
1个回答
0
投票
protected $casts = [ 'data' => 'json' ];

收件人:

 protected $casts = [
           'data' => 'array'
        ];
© www.soinside.com 2019 - 2024. All rights reserved.