How use the attributes of a fabricator within the definition of the fabricator? - fixtures

I have a User and UserProfile models. Currently both models have the attributes first_name, last_name, and email and they must be the same. Later on I will remove these attributes from User but currently I want it that way. A UserProfile belongs_to a User. I have defined the UserProfile fabricator like so:
Fabricator(:user_profile) do
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
email { Faker::Internet.email }
user { Fabricate :user }
end
and the User fabricator:
Fabricator(:user) do
email { Faker::Internet.email }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
last_login_at { Time.now }
organization { Fabricate :organization }
end
The problem is that now, when I fabricate a user profile the attributes are not the same:
user_profile.first_name == user_profile.user.first_name # => false
In the definition of the user profile fabricator I tried this, but it didn't work:
user { Fabricate :user, first_name: first_name, last_name: last_name, email: email }
How can I fabricate a user and a user profile with same attributes without having to replace Faker with hard coded values?

I think the easiest way is to reorganize your user profile a bit and use the data from the user to populate its fields.
Fabricator(:user_profile) do
user
first_name { |attrs| attrs[:user].first_name }
last_name { |attrs| attrs[:user].last_name }
email { |attrs| attrs[:user].email }
end
Fabricator(:user) do
email { Faker::Internet.email }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
last_login_at { Time.now }
organization
end

Related

Prisma delete() function returns "Argument where of type TodoWhereUniqueInput needs at least one argument"

I'm making a call to prisma.delete() function in order to delete a record from my database but I get this error:
Invalid `prisma.todo.delete()` invocation
------
Argument where of type TodoWhereUniqueInput needs at least one argument. Available args are listed in green.
This is the schema.prisma file:
model Todo {
Todo_ID Int #id #default(autoincrement())
Title String? #db.VarChar(255)
Body String? #db.Text
Create_Time DateTime? #db.DateTime(0)
Last_Update_Time DateTime? #db.DateTime(0)
Status Int? #default(0) #db.TinyInt
InRecycleBin Int? #default(0) #db.TinyInt
Username String?
Users Users? #relation(fields: [Username], references: [Username], onDelete: Cascade, onUpdate: NoAction, map: "Todo_ibfk_1")
##index([Username], map: "Username")
}
model Users {
Username String #id #unique(map: "Username") #db.VarChar(255)
Password String #db.VarChar(255)
Todo Todo[]
}
and this is the function I'm trying to execute:
export async function DeleteTodo(todo_Id: number): Promise<Todo | null> {
try {
const result = await prisma.todo.delete({
where: {
Todo_ID: todo_Id,
}
});
if (typeof result !== null) return result;
} catch (err: any) {
console.log(err);
}
return null;
}
Can someone please help? I really don't understand what I'm doing wrong
I tried to use deleteMany() instead of delete() and it works like that, but the return type is different and I really don't understand why it doesn't work with delete()

How is the way for me to transfer data from an ITEM that is related to my salesman in the database?

I have this relationship in my schema:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Salesman {
id String #id #default(uuid())
username String #unique
password String
contact String #unique
item Item[]
##map("salesman")
}
model Buyer {
id String #id #default(uuid())
username String #unique
password String
##map("buyer")
}
model Item {
id String #id #default(uuid())
item_name String
float_item String
price String
type_skin String
salesman Salesman? #relation(fields: [id_salesman], references: [id])
id_salesman String?
##map("item")
}
i try like this
import { prisma } from "../../../../database/prismaClient" interface IRequest{ username: String, contact: String, id: String } export class GetItemUseCase { async execute({ username, contact, id}: IRequest ){ const info = await prisma.item.findFirst({ where:{id}, select:{ salesman { username, contact, }, } }) } } I tried something like this.
and I'm trying to make a way where when choosing an ITEM, I get the data from that salesman.
but I have no idea how.
What better way to inform?
Sorry, I'm a beginner.
I've tried verifying the relationships and I've tried searching the database.

How can cart table associate with another table?

I have table table_name(id, cart_token, data , created_at, updated_at ) that wants to associate with shopware cart table using token column (table_name.cart_token = cart.token).
How can we do this association using DAL as long as cart table doesn't have a CartEntity and CartDefinition.
For example: Select * from table_name leftjoin cart on table_name.cart_token=cart.token where cart.token=null.
Without a definition and accompanying entity class you simply won't be able to retrieve the cart as a mapped object using the DAL. You could add your own definition and entity for the cart table but I wouldn't recommend it, as this would just cause problems if multiple extensions got the same idea. I would recommend injecting Doctrine\DBAL\Connection in a service of your plugin and just fetching the cart using raw SQL.
class CartFetcherService
{
private Connection $connection;
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
public function fetchCart(YourCustomEntity $entity): ?array
{
$cart = $this->connection->fetchAssociative(
'SELECT * FROM `cart` WHERE `token` = :token',
[
'token' => $entity->getToken(),
]
);
return $cart ?: null;
}
}
If you want to retrieve the Cart object directly, you could also inject the Shopware\Core\Checkout\Cart\CartPersister service to load the cart.
class CartLoaderService
{
private CartPersister $persister;
public function __construct(CartPersister $persister)
{
$this->persister = $persister;
}
public function getCart(YourCustomEntity $entity, SalesChannelContext $context): ?Cart
{
try {
$cart = $this->persister->load($entity->getToken(), $context)
} catch (\Throwable $exception) {
$cart = null;
}
return $cart;
}
}

get posts by tag Id using Prisma.js

How can I get posts by filtering tagId?
I test this code but it doesn't work:
I get all of the posts without filtering!
prisma.post.findMany({
include:
{
Tags:
{
where: { TagId: tagId },
include:
{
Tag: true
}
}
},
})
schema.prisma:
model Post {
id Int #id #default(autoincrement())
title String
tags PostTags[]
}
model PostTags {
id Int #id #default(autoincrement())
post Post? #relation(fields: [postId], references: [id])
tag Tag? #relation(fields: [tagId], references: [id])
postId Int?
tagId Int?
}
model Tag {
id Int #id #default(autoincrement())
name String #unique
posts PostTags[]
}
how can I fix the problem?
You would need to filter it inside the main query and not in include. include is only for fetching relations and then filtering inside them, it will not affect the main query.
Your final query would look like:
await prisma.post.findMany({
where: { tags: { some: { tag: { id: 1 } } } }
})
You can read more about querying for relations here.

Kohana 3.1 ORM: joins for has_many

I have a users, messages and comments.
users id user_id
messages id user_id
comments id message_id
I can get users data of the message using with().
$model = ORM::factory('message');
$messages = $model
->with('user')
->find_all();
with('comment') doesn't work. I guess because it's created for one-to-one relations while I have message has_many comment.
How do I get comments data into $messages? Like the following: ['message_id']['comment_id'][DATA]?
0. Define relationships:
User has_many Messages
Message has_many Comments
Message belongs_to User
Comment belongs_to Message
class Model_User extends ORM {
protected $_has_many = array('messages' => array());
}
class Model_Message extends ORM {
protected $_belongs_to = array('user' => array());
protected $_has_many = array('comments' => array());
}
class Model_Comment extends ORM {
protected $_belongs_to = array('message' => array());
}
1. Get user messages:
$messages = ORM::factory('user', $user_id)->messages->find_all();
foreach($messages as $message) {...}
2. Get message owner:
$user = ORM::factory('message', $message_id)->user; // without find_all()!
3. Get message comments:
$comments = ORM::factory('message', $message_id)->comments->find_all();
foreach($comments as $comment) {...}

Resources