我在Laravel中使用此Staudenmein package,并指代包所有者自己给出的答案。
我有两个表,模型为pets
和notifications
的Pet
和Notification
。notifications
表具有名为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的记录。因此,该关系不应为空。
我在做什么错?
protected $casts = [
'data' => 'json'
];
protected $casts = [
'data' => 'array'
];