I have to make this JSON response which every product has colors and each color has many images
[
{
"id": 1,
"name": "shirt",
"descriptions": "lorem epsum",
"colors":[
{
"color_name":"red",
"icon":"1.jpeg",
"images": [
{
"url": "1.png"
},
{
"url": "2.png"
},
{
"url": "3.jpeg"
}
]
},
{
"color_name":"blue",
"icon":"1.png",
"images": [
{
"url": "1.png"
},
{
"url": "2.png"
},
{
"url": "3.png"
}
]
}
]
}
]
How can I make the colors using eloquent relationships?
how many tables and columns with foreign keys should I create?
Here you've to make three tables
products -> Product.php(Model name)
id
name
descriptions
created_at
updated_at
colors -> Color.php(Model name)
id
product_id
color_name
created_at
updated_at
3) images -> Image(Model name)
id
color_id
url
created_at
updated_at
Three model with relationship.
Product.php Model
class Product extends Model
{
protected $table = "products";
//get colors
public function colors(){
return $this->hasMany('App\Color','product_id','id');
}
}
Color.php Model
class Color extends Model
{
protected $table = "colors";
//get product
public function product(){
return $this->belongsTo('App\Product','product_id','id');
}
//get images
public function images(){
return $this->hasMany('App\Image','color_id','id');
}
}
Image.php Model
class Color extends Model
{
protected $table = "images";
//get color
public function color(){
return $this->belongsTo('App\Color','color_id','id');
}
}
Now from product model you can access this colors and images
Controller
$products = App\Product::with('colors.images')->get();
return \Response::json($products->toArray());
Related
I am trying to map the following JSON to my POJO using Jackson. I have the following JSON and following POJOs. kindly let me know how to map the JSON to POJO.
JSON string :
{
"Application": {
"id": "0",
"name": "MyApp",
"users": [
{
"User": {
"id": "2",
"name": "Beth Jones"
}
}
],
"groups": [
{
"Group": {
"id": "1",
"name": "SimpleGroup",
"users": [
{
"User": {
"id": "2",
"name": "Beth Jones"
}
}
]
}
}
]
}
}
The POJO according to the client specification is below :
package com.example.custom;
//import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.example.Application;
import com.example.Group;
import com.example.User;
import java.util.Collection;
//#JsonIgnoreProperties(ignoreUnknown = true)
public class MyApplication extends Application {
private Collection<User> users;
private Collection<Group> groups;
public MyApplication(String id, String name) {
super(id, name);
}
public void setUsers(Collection<User> users) {
this.users = users;
}
public void setGroups(Collection<Group> groups) {
this.groups = groups;
}
#Override
public Collection<User> getUsers() {
return this.users;
}
#Override
public User getUser(String userId) {
for (User user: MyParser.myApp.getUsers()) {
if (user.getId().equals(userId))
return user;
}
return null;
}
#Override
public Collection<Group> getGroups() {
return this.groups;
}
#Override
public Group getGroup(String groupId) {
for (Group group: MyParser.myApp.getGroups()) {
if (group.getId().equals(groupId))
return group;
}
return null;
}
#Override
public String toString() {
return "MyApplication{" +
"users=" + users +
", groups=" + groups +
'}';
}
}
Mapping Logic :
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyParser.myApp = mapper.readValue(rewriter.getText(),MyApplication.class);
The resulting object is not able to capture anything as it is all null. Kindly help. Thanks in advance.
I think you should model your JSON correctly, In the users list you shouldn't specify it again that the key is User, that should be preassumed that a list of users will only contain user, same goes for groups list.
IMHO the JSON should look something like this :
{
"application": {
"id": "0",
"name": "MyApp",
"users": [ . ==> Since this is a user List, it will definitely contains user.
{
"id": "2",
"name": "Beth Jones"
}
],
"groups": [
{
"id": "1",
"name": "SimpleGroup",
"users": [
{
"id": "2",
"name": "Beth Jones"
}
]
}
]
}
}
Now the POJO also needs some modification, I am just adding the bare-minimum POJO.
class Application { <====== Top Level Class
private Long id;
private String name;
private List<User> users; // Application has some Users
private List<Group> groups; // Application has some groups
}
class User {
private Long id;
private String name;
}
class Group {
private Long id;
private String name;
private List<User> users; // Each group has some associated users.
}
Now you can use any standard JSON library for Java and convert your JSON into POJO. This will simplify your structure and you won't face null issues with this structure.
I have a customer table and a user table, they have a M:M relationship set in user_has_customer.
The entire application is a Rest API, and i use extraFields() and GET customers?expand=users to get the connected users when looking at customers.
user_has_customer stores some additional information on when the user was assigned to the customer and a few other fields, and several fields can have the same combination of user and customer. To be able to update or delete a relation, I need the relation id (user_has_customer.id) to be visible when looking at customers.
This function will return the customer, and its related users:
public function getUsers() {
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('user_has_customer', ['customer_id' => 'id'])
->select(['id', 'username']);
}
This function will return the user-customer relationship:
public function getUserRelations() {
return $this->hasMany(UserHasCustomer::className(), ['customer_id' => 'id'])
->select(["id",
"customer_id",
"user_id",
"created_by",
"created_at"]);
}
But i would like to know how i can nest these relations, so the result looks like this:
{
"id": 11148,
....
"users": {
"id": 1,
"user_id": 1,
"added": "2017-08-01 22:23:24"
"user": {
"id": 1,
"username": "admin"
}
}
}
or even like this (like a MySQL join):
{
"id": 11148,
....
"users": {
"id": 1,
"user_id": 1,
"added": "2017-08-01 22:23:24"
"username": "admin"
}
}
For some reason this will not work (the created SQL is correct, but the AR refuse to show the fields from user in the result):
public function getUserRelations() {
return $this->hasMany(UserHasCustomer::className(), ['customer_id' => 'id'])
->joinWith('user', true)
- ->select('*');
}
I am consuming some XML exposed from a REST application and want to expose this as JSON in my own REST service.
Right now I have the following POJO:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"salesMarket"
})
#XmlRootElement(name = "salesMarkets")
public class SalesMarkets {
protected List<SalesMarket> salesMarket;
public List<SalesMarket> getSalesMarket() {
if (salesMarket == null) {
salesMarket = new ArrayList<SalesMarket>();
}
return this.salesMarket;
}
}
Which produces the following JSON:
"salesMarkets": {
"salesMarket": [
{
"brands": {
"brand": [
"DAN"
]
},
"code": "999"
},
{
"brands": {
"brand": [
"DAN"
]
},
"code": "208"
}
]
}
My question is (using Jackson annnotations), is there a way to avoid the class name being serialized as JSON??, so I instead would have:
"salesMarket": [{
"brands": {
"brand": [
"DAN"
]
},
"code": "999"
}, {
"brands": {
"brand": [
"DAN"
]
},
"code": "208"
}]
I'm thinking some Jackson annotaion on the class SalesMarkets... But havn't been succesfull yet :-(
UPDATE:
Just realised that the SalesMarket class was referenced from another class - which is why the "salesMarkets" appears in the JSON. Is there a way to annotate the SalesMarkets field, so that it is ignored but not the fields contained there in?:
#XmlRootElement(name = "product")
public class Product {
#XmlElement(required = true)
protected String propertyID;
#XmlElement(required = true)
protected String season;
**protected SalesMarkets salesMarkets;**
protected Information information;
protected Features features;
protected Location location;
protected Address address;
protected Buildings buildings;
protected Pictures pictures;
protected Media media;
protected Prices prices;
protected Offers offers;
protected Availabilities availabilities;
protected Services services;
protected Concepts concepts;
...
You need to either remove
#XmlRootElement(name = "salesMarkets")
Or disable the feature on ObjectMapper:
objectMapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true)
To further unwrap salesMarkets field in Product instances you can do the following:
public class Product {
protected SalesMarkets salesMarkets;
public List<SalesMarket> getSalesMarkets(){
if(salesMarkets != null){
return salesMarkets.getSalesMarket();
} else {
return null;
}
}
}
I'm trying to return a JSON of data stored in my database, it works but it does not show the name of the array.
I'm using Laravel.
My code :
<?php
class PlayerController extends BaseController {
public function checkupdate()
{
$datapack = DB::table('datapack')->get();
if (Request::isJson()) {
return Response::json($datapack,200);
}
return Response::json($datapack,200,[],JSON_PRETTY_PRINT);
//return View::make('view');
}
}
which give me :
[
{
"id": "FD314",
"timeUpdated": 1401184091
}
]
and I want something like this :
[
"datapack" : {
"id": "FD314",
"timeUpdated": 1401184091
}
]
Just add it under a datapack key
return Response::json(['datapack'=>$datapack],200);
Hi all i have a Database where i have some tables named
[Options],[ProductAttributes],[Products],[ProductSKU],[ProductSKUOptionMappings]
i had added this as entity model to my project,now i want to write a linq query for this where i can get these column from the above specified tables
based on this stored procedure
ALTER procedure [dbo].[GetProductDetail]
(
#ProductID bigint
)
as
begin
Select P.ProductName, P.ProductDescription, PA.SKU, PA.OptionId,O.OptionName, PA.Value, PS.ImageURL from ProductSKU PS
INNER JOIN ProductAttributes PA ON PS.SKU = PA.SKU
INNER JOIN Products P ON P.ProductId = PS.ProductId
INNER JOIN Options O ON O.OptionsId = PA.OptionId
WHERE PS.ProductId = #ProductID
end
i want to convert this query into linq query or use this as Storedprocedure to get my required Json object
the output of my stored procedure looks like this
ProductName ProductDescription SKU OptionId OptionName Value ImageURL
Tactical Long Sleeve Shirts Hemline side slits Shirt_1001 1 Color Grey C:\Users\Administrator\Desktop\Images\LongSleeveShirt.jpg
Tactical Long Sleeve Shirts Hemline side slits Shirt_1001 2 Size S C:\Users\Administrator\Desktop\Images\LongSleeveShirt.jpg
Tactical Long Sleeve Shirts Hemline side slits Shirt_1001 3 Fit Regular C:\Users\Administrator\Desktop\Images\LongSleeveShirt.jpg
each product may have different SKUs like the above so can any one help me here how can i build my json object which looks like this
i want my json object to be in this format
var productdetails={
"productId": "1",
"productname": "Casualshirts",
"productSkus": [
{
"Skuimage": "URL",
"SKU": [
{
"ProducSKU": "Shoe1001",
"Options": [
{
"productOptions": [
{
"OptionID": "1",
"optionname": "Color",
"value": "Black"
},
{
"OptionID": "2",
"optionname": "Size",
"value": "S"
},
{
"OptionID": "3",
"optionname": "Fit",
"value": "Regular"
}
]
}
]
},
{
"ProducSKU": "Shoe1002",
"Options": [
{
"productOptions": [
{
"OptionID": "1",
"optionname": "Color",
"value": "Black"
},
{
"OptionID": "2",
"optionname": "Size",
"value": "S"
},
{
"OptionID": "3",
"optionname": "Fit",
"value": "Regular"
}
]
}
]
},
{
"ProducSKU": "Shoe1003",
"Options": [
{
"productOptions": [
{
"OptionID": "1",
"optionname": "Color",
"value": "Black"
},
{
"OptionID": "2",
"optionname": "Size",
"value": "S"
},
{
"OptionID": "3",
"optionname": "Fit",
"value": "Regular"
}
]
}
]
}
]
and here is my model class
public class ProductItems
{
public long ProductID { get; set; }
public string ProductName { get; set; }
public string ImageURL { get; set; }
public List<productSKU> SKUs { get; set; }
}
public class productSKU
{
public string productsku { get; set;}
public string SKUImageURL { get; set;}
public List<options> oPTIONS { get; set; }
}
public class options
{
public long OptionID { get; set; }
public string OptionName { get; set;}
public string OptionValue { get; set;}
}
can any one help me in how to construct my stored procedure or linq query as above json pbjkect thanks in advance...
this is how i am trying to bind my data to my model
public IEnumerable<ProductItems> ProductDeatils(long ProductID)
{
var productdeatils = products.ExecuteStoreQuery<ProductItems>("GetProductDetail #ProductID ", new SqlParameter("#ProductID", ProductID));
var data=new List<ProductItems>();
foreach (var prod in productdeatils)
{
ProductItems items = new ProductItems();
items.ProductID = prod.ProductID;
items.ProductName = prod.ProductName;
items.SKUs
}
return data;
}
i am stuck with number of properties in my class and number of Database columns i amn retrieving from my procedure how can i map them to my model
Assuming you have retrieved an instance of your ProductItems model from your data layer you could project it into an anonymous object to be passed to a JsonResult in order to achieve the desired JSON structure:
public ActionResult SomeAction()
{
ProductItems model = ... retrieve the model from your data layer
var result = new
{
productId = model.ProductID,
productname = model.ProductName,
productSkus = model.SKUs.Select(sku => new
{
Skuimage = sku.SKUImageURL,
SKU = new[]
{
new
{
ProducSKU = sku.productsku,
Options = new[]
{
new
{
productOptions = sku.oPTIONS.Select(opt => new
{
OptionID = opt.OptionID,
optionname = opt.OptionName,
value = opt.OptionValue
})
}
}
}
}
})
};
return Json(result, JsonRequestBehavior.AllowGet);
}