Laravel relationship is being inserted in the collection - eloquent

I created the following accessors to check the agency property:
public function getIsAgencyAttribute() {
// agency is a boolean value
return isset( $this->ref->agency ) && $this->ref->agency;
}
// relationship
public function ref() {
return $this->hasOne(SellerRef::class, 'user_id');
}
I call the append() method:
$query = User::query();
// a bunch of when conditions...
// $query->when(...);
$data = $query->limit( $request->limit ?: config('app.limit_per_page') )->get();
$data->append('is_agency');
return response()->json( responseFormat( false, $data ) );
expected response:
{
"id": 5,
"name": "mariana",
"email": "mariana#email.com",
"blocked_at": null,
"deleted_at": null,
"created_at": "2021-03-05T02:44:46.000000Z",
"is_agency": false
}
current response:
{
"id": 5,
"name": "mariana",
"email": "mariana#email.com",
"blocked_at": null,
"deleted_at": null,
"created_at": "2021-03-05T02:44:46.000000Z",
"is_agency": false,
"ref": {
"user_id": 5,
"code": "OZO33T",
"agency": false
}
}
why is the ref property being inserted in the collection?
if a remove $data->append('is_agency'); ref disappear..

Solution:
//change
public function getIsAgencyAttribute() {
return isset( $this->ref->agency ) && $this->ref->agency;
}
// to this
public function getIsAgencyAttribute() {
return isset( $this->ref()->first()->agency ) && $this->ref()->first()->agency;
}

Related

How to update jarray in jsonb field?

I have a jsonb field that contained the something like below:
How to update is_read properties in extras node to true where the users_pid = 1 and is_read=false?
I have tried below:
UPDATE chats
SET attributes = jsonb_set(
cast(attributes->'data'->>'extras' AS jsonb),
array['is_read'],
to_jsonb(true)
)
WHERE users_pid =1
AND cast(attributes->'data'->'extras_to'- >>'is_read' AS boolean) = false
but nothing updated
[
{
"data": {
"users_pid": 1,
"datetime": "2022-05-01 13:10:58",
"extras": {
"is_read": false,
"read_dt": ""
}
}
},
{
"data": {
"users_pid": 3,
"datetime": "2022-05-23 11:03:22",
"extras": {
"is_read": false,
"read_dt": ""
}
}
},
{
"data": {
"users_pid": 1,
"datetime": "2022-05-13 11:23:22",
"extras": {
"is_read": false,
"read_dt": ""
}
}
}
]

Search Key in Nested json in Dart/Flutter

I want to search the key "AylaHeartBeatFrequency" inside nested json. how to search and get its value ? in flutter/dart
{
"sAWSIoT": {
"CloudStatus": 1,
"PairingFlag": 0,
},
"sDebug": {
"LocalDebugMsg_d": "Model ID",
"AylaHeartBeatFrequency": 0
},
"Product": {
"Mode": 1,
"Model": "abc"
},
"data": {
"DeviceType": 300,
"Endpoint": 0,
"UniID": "0000000000000000"
}
}
You can do:
var map = /*put your json here. You can use json.decode() on the json if it's not yet formatted*/, value;
for(var item in map.values) {
if(item.containsKey('AylaHeartBeatFrequency') value = item['AylaHeartBeatFrequency']) ;
}

Sequelize nested include without null properties

using ExpressJs/Postgres/Sequelize and when doing findOne I am getting an object return that contains nested objects with following data in the response:
"CompanyVolume": null,
"CompanyMarkets": [],
Is there a way to avoid receiving these properties with null/[] from Postgres?
Appreciate any thoughts...:)
const kyc = await db.Kyc.findOne({
where: {id: req.params.id},
include: [
{model: db.Company,
include: [
{ model: db.CompanyStakeholder, through: db.Role },
{ model: db.CompanyDelivery,
// where: {
// deliveryAverageDurationAmount: {[Op.not]:null},
// }
//returns Cannot read properties of undefined (reading 'not')
},
{ model: db.CompanyVolume },
{ model: db.CompanyDelivery },
{ model: db.CompanyMarket },
],
nest: true,
})
the response object with properties including null or empty arrays
[
{
"id": 5,
"kycTitle": "KYC1006428",
"kycPasscode": null,
"kycDescription": "The best kyc ever, lorem epsum sanctus vita loca",
"kycStartDate": "2022-01-28",
"kycStatus": null,
"kycConsent": "approved",
"kycConsentDate": "2022-01-27T14:01:39.924Z",
"createdAt": "2022-01-27T13:19:41.649Z",
"updatedAt": "2022-01-27T14:01:39.919Z",
"id_User": 1,
"Company": {
"id": 6,
"companyName": "Niky",
"companyEntityType": null,
"companyVatNumber": "",
"companyRegistrationNumber": "",
"companyPubliclyListed": null,
"companyAddress1": "Pepovej 234",
"companyAddress2": "",
"companyCity": "Dada",
"companyPostCode": "3400",
"companyCountry": "Owner",
"companyPhone": "+21321321231",
"createdAt": "2022-01-27T13:19:41.669Z",
"updatedAt": "2022-01-27T13:19:41.676Z",
"KycId": 5,
"CompanyStakeholders": [], //I don't want this returned
"CompanyDelivery": null, //I don't want this returned
"CompanyVolume": null, //I don't want this returned
"CompanyMarkets": [], //I don't want this returned
},
}
]
The different Associations:
Company.associate = function (models) {
Company.hasOne(models.Contact)
Company.hasOne(models.CompanyDelivery)
Company.hasMany(models.CompanyMarket)
Company.hasMany(models.CompanyPosBilling)
Company.hasMany(models.CompanySettlement)
Company.hasOne(models.CompanySubscription)
Company.hasOne(models.CompanyVolume)
Company.hasMany(models.CompanyWebsite)
Company.belongsTo(models.Kyc)
Company.belongsToMany(models.CompanyStakeholder, {
through: models.Role,
unique: false
})
}
CompanyDelivery.associate = function (models) {
CompanyDelivery.belongsTo(models.Company)
}
CompanyMarket.associate = function (models) {
CompanyMarket.belongsTo(models.Company)
}
Kyc.associate = function (models) {
Kyc.hasOne(models.Company)
}
CompanyStakeholder.associate = function (models) {
CompanyStakeholder.belongsToMany(models.Company, {
through: models.Role,
unique: false
})
}

How can I paginate using Resource<T> using Page<T>

I am using the following code to create a paginated list of JSON data for Artist objects:
#RequestMapping(value = "/artists/all", method = RequestMethod.GET, produces = {"application/hal+json"})
public Resources<Artist> getArtists(Pageable pageable) {
final Page<Artist> allArtists= artistService.GetAllArtists(pageable);
for (final Artist artist : allArtists) {
Long artistId = artist.getArtistId();
Link selfLink = linkTo(methodOn(ArtistController.class).getAllArtistById(artistId)).withSelfRel();
artist.add(selfLink);
final Link ordersLink = linkTo(methodOn(MusicController.class).getMusicByArtistId(artistId, pageable)).withRel("musics");
artist.add(ordersLink);
}
Link link =linkTo(ArtistController.class).withSelfRel();
Resources<Artist> result = new Resources<>(allArtists,link);
return result;
}
The code currently returns outputs that are in this format:
{
"artistId": 2,
"name": "Simon Mburu",
"_links": {
"self": {
"href": "http://localhost:8000/api/v1/artists/2"
},
"musics": {
"href": "http://localhost:8000/api/v1/musics/artist/2"
}
}
}
However my intent is to have the code return an output like this:
"pageable": {
"sort": {
"sorted": false,
"unsorted": true
},
"offset": 0,
"pageSize": 20,
"pageNumber": 0,
"paged": true,
"unpaged": false
},
"last": true,
"totalPages": 1,
"totalElements": 2,
"size": 20
"number": 0,
"numberOfElements": 2
"sort": {
// ETC...
What changes can I make to my code to get it to output the data contained in the above example instead of what it currently outputs?

Setting extraFields in rest api yii2

public function fields()
{
return [
'field' => 'field',
];
}
public function extraFields()
{
return [
'users',
];
}
return:
{ "field": "field", "users": { "id": 1, "name": "user" } }
how to exclude id?
public function extraFields()
{
return [
'users' => function($model){
return [
'name' => $model->users->name,
];
}
];
}
return:
{ "field": "field", "users": { "name": null } }
how to fill in the name field correctly or how to customize field output filtering?
Option can be overwrite field() method in User model:
public function fields()
{
$fields = parent::fields();
if ($something) {
unset($fields['id']);
}
return $fields;
}