Many to many in laravel not working - database

My User model code is
public function companies()
{
return $this->belongsToMany('App\Company');
}
My companies table has below field
id
company_name
company_address
company_phone
created_at
updated_at
and My company_user table has below field
user_id
company_id
created_at
updated_a
My Company model has below code
public function users()
{
return $this->belongsToMany('App\User');
}
When I call
$user=Auth::user()->companies;
It shows nothing. But My company has data. also, my company_user table has appropriate data. What is the problem

Related

Prisma: What would be the best way to create relationships between 3 tables?

I have the following models.How can I create a relationship for these tables so that I can get the roles associated with group and group associated with roles.One group will have multiple roles.
Groups and Roles will be added separately though.Only after the Group is added can the roles be associated with them
model groups {
id Int #id #default(autoincrement())
group_name String? #unique
}
model roles {
id Int #id #default(autoincrement())
role_name String? #unique
}
model group_role_association {
id Int #id #default(autoincrement())
group_id Int
role_id Int
}
This seems like a use case for an implicit relation. This is a feature of Prisma that allows you to model a m-n relatinshiop between to tables without managing a relation table (in your example, I read group_role_association to be a relation table rather than an actual "model")?
model groups {
id Int #id #default(autoincrement())
groups_name String
roles roles[]
}
model roles {
id Int #id #default(autoincrement())
role_name String
groups groups[]
}
Also, I'd actually recommend you to use Prisma's naming conventions (i.e. spell model names in singular form and PascalCase notation):
model Group {
id Int #id #default(autoincrement())
name String
roles Role[]
}
model Role {
id Int #id #default(autoincrement())
name String
groups Group[]
}

Get GORM model row based on foreign key relationship (golang)

I am using Golang (GORM) + Postgres. I am trying to model a business situation where a seller sells things to buyers, each creating an order transaction.
I have an Order Gorm model, as well as a Buyer and a Seller Gorm model. The Buyer and the Seller are already rows created in the database.
One buyer HasMany orders.
One seller HasMany orders.
To map out this relation, I believe I just create the respective Buyer/Seller struct (standard Gorm models), and then make an Order struct like so:
type Order struct {
ID int64 `json:"ID"gorm:"primary_key;auto_increment:true"`
Buyer *Buyer `json:"Buyer"`
Seller *Seller `json:"Seller"`
// ... other data ...
}
I'm assuming the above automatically creates the relationship, but I am not entirely sure. I can create an Order with this function, and this returns fine:
func CreateOrder(buyer *entity.Buyer, seller *entity.Seller) (*entity.Order, error) {
order := &entity.Order{
User: buyer,
Sitter: seller,
// ... other data ...
}
db.Table("orders").Create(order)
return order
}
If I go to Postgres CLI, the TABLE orders; does not show the columns buyer or seller. I would expect a column of their IDs. So this is why I am unsure this is working. This could definitely be a problem in itself.
Anyways, what I really want to do is be able to check if any orders currently exist for a Buyer / Seller. But I don't really see anyway to do that with gorm queries. I would imagine in SQL it would be something like:
func FindOrder(buyer *entity.Buyer, seller *entity.Seller) {
db.Raw(`GET order FROM orders WHERE buyer = ?, seller = ?`, buyer, seller)
// OR this ???
db.Table("orders").First(buyer, buyer).First(seller, seller)
}
But I don't know of any Gorm helper function that actually does this. I also want this to be efficient because buyer and seller each have their ID primary keys.
How can I find an Order based on the Buyer / Seller like in the example above?
As an alternative, I am thinking of adding (buyer ID + seller ID) to make a custom order ID primary_key. This seems hacky though, as I feel like the whole point of relations is so I don't have to do something like this.
If you need to see the seller id and the buyer id in the orders table, include two fields for that in your orders struct, also you can use the foreignKey tag to populate those fields (by default they are populated with the primary id of the associated table record, you can use references tag as mentioned here to change that).
type Order struct {
ID int64 `json:"id" gorm:"primaryKey;autoIncrement:true"`
BuyerID int64 `json:"buyer_id" gorm:"index"`
SellerID int64 `json:"seller_id" gorm:"index"`
Buyer *Buyer `json:"buyer" gorm:"foreignKey:BuyerID"`
Seller *Seller `json:"seller" gorm:"foreignKey:SellerID"`
}
type Buyer struct {
ID int64 `json:"id" gorm:"primaryKey;autoIncrement:true"`
Name string `json:"name"`
}
type Seller struct {
ID int64 `json:"id" gorm:"primaryKey;autoIncrement:true"`
Name string `json:"name"`
}
As for the function to find orders given the buyer AND the seller you can use something like,
func findOrders(db *gorm.DB, buyerID int,sellerID int)[]Order{
orders := make([]Order,0)
db.Where("buyer_id=? AND seller_id=?",buyerID,sellerID).Find(&Order{}).Scan(&orders)
return orders
}
in contrast if you need to find orders for a given buyer OR the seller,
func findOrder(db *gorm.DB, buyerID int,sellerID int)[]Order{
orders := make([]Order,0)
db.Where("buyer_id=? OR seller_id=?",buyerID,sellerID).Find(&Order{}).Distinct().Scan(&orders)
return orders
}
The index tag covers the indexing requirement for orders table.
Use simple raw query builder for large queries
https://perfilovstanislav.github.io/go-raw-postgresql-builder/#simple-example

Laravel belongsToMany with more then 3 primary keys

Actually I'm confused for the case, which relation fits best for my case, and in my opinion the best one is to have a table with 3 primary keys.
To be more specific.
I have a Person model in one of my db's, which has structure like
Person:
Id,
FirstName,
LastName,
...
And the other model Department, which has structure mentioned below
Department:
Id,
Name,
Description,
...
And goal is to set up Editors of schedule for each department and add also admins, whioch will approve requested schedules from editors. Editors and Admins are from same Person table, and if to assume, we need to map some Persons and department with some type.
I'm thinking about to have a mapping table with structure
PersonID,
DepartmentID,
Type (editor or admin)
And not sure, which relation fits best for this. If to have belongsToMany relation here with primary keys PersonID and DepartmentID, we will face an issue, because same Person possibly can be as editor and as admin for one single department. I have MS SQL server as a db.
Any suggestions will be appreciated
you can define many to many relations and use wherePivot method to select by pivot table Type column:
// Department model
public function admins()
{
return $this->belongsToMany(Person::class)->wherePivot('type', 'admin');
}
public function editors()
{
return $this->belongsToMany(Person::class)->wherePivot('type', 'editor');
}
// Person model
public function departmentsWhereIsAdmin()
{
return $this->belongsToMany(Department::class)->wherePivot('type', 'admin');
}
public function departmentsWhereIsEditor()
{
return $this->belongsToMany(Department::class)->wherePivot('type', 'editor');
}
// Note: we use methods names without parentheses
// usage for department
$department = Department::first(); // for example
dump($department->admins);
dump($department->editors);
// usage for person
$person = Person::first(); // for example
dump($person->departmentsWhereIsAdmin);
dump($person->departmentsWhereIsEditor);

laravel 5.4 many to many relationship

i have relationship many to many table 'admins' , 'pjt_roles' with pjt_role_admin.
but,not working
i have 2 model
class Role
protected $table = 'pjt_roles';
public function Admin(){
return $this->belongsToMany(Admin::class',pjt_role_admin');
}
class Admin
public function Role(){
return $this->belongsToMany(Role::class,'pjt_role_admin');
}
and table pjt_role_admin have attribute
admin_id from table admins
role_id from table pjt_roles
Specify your pivot table in relationship. Default laravel assume admin_role as your pivot table because you have Admin and Role models
class Role
protected $table = 'pjt_roles';
public function Admin(){ // should be admins() for better readability
return $this->belongsToMany(Admin::class, 'pjt_role_admin');
}
class Admin
public function Role(){ // should be roles() for better readability
return $this->belongsToMany(Role::class, 'pjt_role_admin');
}
To determine the table name of the
relationship's joining table, Eloquent will join the two related model
names in alphabetical order. However, you are free to override this
convention. You may do so by passing a second argument to the
belongsToMany method.
Fetch Data
$admin = Admin::find(1);
$roles = $admin->Role; // should change to roles() in relationship for better readability
Save
$admin->Role()->attach($roleId);
details https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

Error when creating a new Customer - MVC ADO.NET

I get the following error when I fill out my form in my MVC Application:
UpdateException was unhandled by user code
Unable to update the EntitySet 'Customer' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
My Customer table has: ID (PK), Name, Age, Address and a TimeStamp.
The form only allows Name and Address to be filled out (don't know why - I'm new to MVC, ADO.NET btw)
This is my code:
[HttpPost]
public ActionResult Create(Customer customer)
{
customer.ID = 5;
db.Customers.AddObject(customer);
db.SaveChanges();
return View();
}
I am leaving customer.ID = 5 as a hard coded temp solution for the time being.
If ID is your primary key, Why you are updating that ? You should be updating the rest of the properties.
[HttpPost]
public ActionResult Create(Customer customer)
{
customer.Name= "New name";
db.Customers.AddObject(customer);
db.SaveChanges();
return View();
}
Do you have primary key in your Customer Table ?
This error originates when you do not have primary key on table or when your entity set is mapped with database view.

Resources