When I include the Categories table in the seller table with Ef Core, it comes with Product in the Category, I just want the category table to come. There is an overload of data. How can i solve it. Why does Products also appear in Category under Seller only? I just wrote .Include(Category), Products should not come??
The function I included
public async Task<IResponse<Seller>> GetByIdAsyncR(int id)
{
var data = await _context.Sellers.Where(i => i.Id == id)
.Include(i => i.Categories)
.Include(i => i.AppUsers)
.Include(i => i.Products)
.Include(i => i.Orders)
.FirstOrDefaultAsync();
if (data != null)
return new Response<Seller>(ResponseType.Success, data);
return new Response<Seller>(ResponseType.NotFound, "Data bulunamadı");
}
This is the result
{
"email": "a1#a.com",
"offers": [],
"categories": [
"name": "cat1",
"description": "des1",
"language": 0,
"sellerId": 1,
"imageId": null,
"image": null,
"products": [
{
"name": "pd 1",
"language": 0,
"description": "desdesdesdesdesdesdesdesdesdesdesdesdesdesdesdesdesdesdesdes1",
"isStock": true,
"isNew": true,
"sellerId": 1,
"categoryId": 1,
"orderItems": [],
"images": [],
"cardItems": [],
"menuProduct": [],
"id": 1,
"createdDate": "2023-02-13T01:52:17.5190827"
}
],
"id": 1,
"createdDate": "2023-02-13T01:52:17.5190795"
}
I don't understand why Seller->Category->Product is coming?
Shouldn't the Products under Category be empty?
I couldn't understand why Products is empty under Category. Shouldn't it be null?
This is a normal query result. Include() tells EF that you want to pull child records for processing. If you don't want child entities, don't use Include.
Like as Svyatoslav Danyliv said, you can add AsNoTracking to your query:
var data = await _context.Sellers.Where(i => i.Id == id)
.Include(i => i.Categories)
.Include(i => i.AppUsers)
.Include(i => i.Products)
.Include(i => i.Orders)
.AsNoTracking()
.FirstOrDefaultAsync();
AsNoTracking() allows you to tell Entity Framework Core not to track the results of a query. This means that Entity Framework Core performs no additional processing or storage of the entities which are returned by the query.
If you want to use Select(), you can refer to the following code to feel the query results of Select more intuitively:
var data = await _context.Sellers.Where(i => i.Id == id)
.Select(x => new {
ParentRecord = x,
ChildRecord = x.Categories,
HasChildRecords = x.Categories.Any()
})
.Include(i => i.AppUsers)
.Include(i => i.Products)
.Include(i => i.Orders)
.FirstOrDefaultAsync();
Hope this can help you.
Related
I got a query that gets the data into a collection, problem is that it shows foreign id but i want it to display what i have given in the url parameters.
columnsGiven is the parameter from url. contains column names with child: "language.name". so column=active,title,language.name
For example i get this:
"name": "george",
"active": 1,
"language": 1,
and this is what i want:
"name": "george",
"active": 1,
"language": "Dutch",
this is my code:
public function index(Request $request){
$columnsGiven = explode(',', $request->columns);
$tableName = $request->table_name; //example: 'support_guide_translations'
$modelName = $request->model_name; //example: "App\Models\SupportGuideTranslation";
if($request->search){
$query = $modelName::search($request->search);
} else{
$query = $modelName::query();
if($request->sort){
$sort = explode('?', $request->sort);
$query->orderBy($sort[0], $sort[1]);
}
}
foreach ($request->query() as $key => $value) {
// dd($value);
if(!$value == ""){
if(Schema::hasColumn($tableName, $key)){
$query->where($key, $value);
}
if(in_array($key, $columnsGiven)){
dd('true');
}
// $searchWord = Str::contains('account123',$request->search);
}
}
$guides = $query->get();
return GuideResource::collection($guides);
}
}
this is GuideResource, it sends data to vue by making it json first. Not allowed to make changes here, it has to be done in the function index. :
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'body' => $this->body,
'active' => $this->active,
'language' => $this->language,
'support_guide' => $this->support_guide,
'support_guide_group' => $this->support_guide_group,
];
}
"language": {
"id": 1,
"name": "Dutch",
"code": "NL",
"created_at": "2021-06-14T10:10:32.000000Z",
"updated_at": "2021-06-14T10:10:32.000000Z"
},
I believe "language" has a relationship with another model.
Isn't this what you are looking for?
return [
// your other attributes...
'language' => $this->language->relationshipName->name,
];
where relationshipName is the method name in the Language model.
I have a database storing some videogames. Each of them has three release dates: one for Europe, another for America and a last one for Japan.
I would like to allow users of my GraphQL API to search for games according to these dates. For exemple, in order to get name and release date of games released in Europe and America but not released in Japan, we can write this query:
{
games(has_been_released: { eur: true, usa: true, jap: false }) {
data {
name
release_date
}
}
}
Therefore, if we want to fetch games released in all regions, the query will be this one:
{
games(has_been_released: { eur: true, usa: true, jap: true}) {
data {
name
release_date
}
}
}
When all booleans have the same value, I would like to simplify the query so that we could write the below instead:
{
games(has_been_released: true) {
data {
name
release_date
}
}
}
In order to do that, I've tried this type definition for field has_been_released (with graphql-php):
<?php
$regionalizedBooleanInput = new InputObjectType([
'name' => 'RegionalizedBooleanInput',
'description' => 'An object with properties "eur", "usa" and "jap" as booleans',
'fields' => [
'eur' => ['type' => Type::boolean(), 'defaultValue' => null],
'usa' => ['type' => Type::boolean(), 'defaultValue' => null],
'jap' => ['type' => Type::boolean(), 'defaultValue' => null],
]
]);
$booleanOrRegionalizedBooleanInputType = new UnionType([
'name' => 'BooleanOrRegionalizedBooleanInput',
'description' => 'A boolean that can be different according to regions',
'types' => [
Type::boolean(),
$regionalizedBooleanInput,
],
'resolveType' => function($value) use ($regionalizedBooleanInput) {
if ($value->type === 'boolean') {
return Type::boolean();
}
return $regionalizedBooleanInput;
},
]);
But when I do that, GraphiQL throws this error:
Error: Introspection must provide object type for possibleTypes.
at invariant (chrome-extension://fkkiamalmpiidkljmicmjfbieiclmeij/dist/chromeiql.js:14605:11)
at getObjectType (chrome-extension://fkkiamalmpiidkljmicmjfbieiclmeij/dist/chromeiql.js:72489:80)
at Array.map ()
at buildUnionDef (chrome-extension://fkkiamalmpiidkljmicmjfbieiclmeij/dist/chromeiql.js:72566:47)
at buildType (chrome-extension://fkkiamalmpiidkljmicmjfbieiclmeij/dist/chromeiql.js:725
So I assume something is wrong with my types definition, but I don't get why. Any ideas?
tl;dr: I would like to have a GraphQL field which can accept a scalar value or an InputObject with this scalar type as fields. Is it even possible?
Thanks in advance!
GraphQL currently doesn't support polymorphic input type or Union in input .
https://github.com/graphql/graphql-spec/issues/488
One solution could be all_regions to part of input schema but not mandatory
input Regions{
eur: Boolean
usa: Boolean
jpa: Boolean
all_regions: Boolean
}
{
games(has_been_released: { all_regions: true}) {
data {
name
release_date
}
}
}
I am using code below to fetch reactions for an activity (with getstream laravel):
$lookupField = "activity_id";
$lookupValue = "aaaaaa";
$reactionType="comment";
$params = array(
'limit' => 5,
"id_lt" => $idLt,
'with_activity_data' => 0,
'with_own_children' => 1,
//'withOwnChildren' => 1,
"user_id" => 11111
);
$reactions = $this->feedClient->reactions()->filter($lookupField, '' . $lookupValue, $reactionType, $params);
The parameter with_own_children does not seem to work. The response I receive from getstream does not contain "own_children".
I have seen this next link in the GET feed response (with own and with_own_children reactions):
"latest_reactions_extra": {
"comment": {
"next": "https://stream-io-api.com/api/v1.0/reaction/activity_id/d4681800-a5a5-xxxx-8080-8001531b6e42/comment/?id_lt=2a012414-6842-460a-bccc-0eb1bac998xx&limit=5&withOwnChildren=true"
}
},
Is there a way to load reactions withOwnChildren using the reactions API?
I want to ask, how to hidden a name in role login.
So I have a output in laravel like this:
{
"npp":"822345",
"nama":"Handra Pratama",
"bus_pergi":1,
"bus_pulang":4,
"hotel":null,
"kamar":"K1",
"teman_kamar":[
{
"nama":"Handra Pratama"
},
{
"nama":"Louis Vernando"
},
{
"nama":"Hallo Budi"
}
]
}
I want to hide role handra (because I'm login with handra username) in teman_kamar, and if i login role louis, i want to hide louis in teman_kamar, what should i do?
Your output is in JS, so you can use a filter function in JS. But if you want to do it in PHP here is an example that I ran and it works per your case, because you always have the name that you want to hide under the first name key.
<?php
$obj = [
"npp" => "822345",
"nama" => "Handra Pratama",
"bus_pergi" => 1,
"bus_pulang" => 4,
"hotel" => null,
"kamar" => "K1",
"teman_kamar" => [
[
"nama" => "Handra Pratama"
],
[
"nama" => "Louis Vernando"
],
[
"nama" => "Hallo Budi"
]
]
];
$obj['teman_kamar'] = array_filter($obj['teman_kamar'], function($val) use ($obj) {
return $val['nama'] !== $obj['nama'];
});
print_r($obj);
I am making a web service in Laravel which is returning JSON.
I have created an Account model like so:
class Account extends Eloquent {
// The database table used by the model.
// (If not defined then lowercase and plural of class name is consider as a table name)
protected $table = "account";
// define which column can be mass assign
protected $fillable = array("user_id", "account_group_id", "generated_by", "image", "name",
"address", "zip", "area_id", "mobile", "email", "phone", "fax",
"website", "pan", "cst", "tin", "ecc", "iesc", "transport",
"other", "outstanding", "cform", "status", "mitp");
// To prevent column from mass assignment.
protected $guarded = array('id');
// Change Variable for CREATED_AT and UPDATED_AT
const CREATED_AT = 'itp';
const UPDATED_AT = 'utp';
}
I am fetching fields from Account using user_id and returning JSON via Response::json() in my controller
$accountData = Account::select('name', 'status', 'id', 'user_id', 'utp')->where('user_id', Auth::id())->first();
$return = array(
'result' => 'success',
'msg' => 'Login Successfully.',
'data' => $accountData
);
return Response::json($return);
In this, utp behaves as expected and returns a date as a string:
{
"result": "success",
"msg": "Login Successfully.",
"data": {
"name": "Demo",
"status": 0,
"id": 143,
"user_id": 207,
"utp": "2015-07-01 18:38:01"
}
}
However if I take each value separately from the account model like so:
$return = array(
'result' => 'success',
'msg' => 'Login Successfully.',
'data' => $accountData['user_id'],
'account_id' => $accountData['id'],
'utp' => $accountData['utp'],
'usertype' => 'account',
'status' => $accountData['status']
);
Then this gives some unexpected behavior from utp
{
"result": "success",
"msg": "Login Successfully.",
"data": 207,
"account_id": 143,
"utp": {
"date": "2015-07-01 18:38:01",
"timezone_type": 3,
"timezone": "Asia\\/Kolkata"
},
"usertype": "account",
"status": 0
}
Why does this happen with my timestamp field?
Because utp is a Carbon\Carbon instance. Model::toJson (actually Model::toArray, but both are used) handles that usually, and serializes a date to it's usual ISO3601-ish format
For expected behavior, you need to format the Carbon instance.
"utp" => $accountData['utp']->format("Y-m-d H:i:s"),
Alternatively, cast it to a string
"utp" => (string) $accountData['utp'],