Eloquent Relation with foreign key - eloquent

I have issues by connecting to tables
I have 2 Model
First Model called PodioBorgerNotat with columns in the table called podio_borger_notats
id
user_id
item_id
app_item_id
borger_item_id (foreign key) 🔐
medarbejder_item_id
status
The second Model called PodioBorgerStamark with columns in the table podio_borger_stamarks
id
item_id (local key) 🔑
app_item_id
status
initials
name
I want to make a connection between PodioBorgerNotat and PodioBorgerStamark
so this is what I do in PodioBorgerNotat Model
public function borger()
{
return $this->belongsTo(PodioBorgerStamark::class, 'borger_item_id', 'item_id');
}
Now I want to output the result by executing this output
$borgernotater = PodioBorgerNotat::orderBy('created_at', 'acs')->orderBy('id', 'desc')->with('PodioBorgerStamark')->paginate(10);
This wont work and i get this error messsage
Call to undefined relationship [PodioBorgerStamark] on model [App\PodioBorgerNotat].

Your relation name is borger:
public function borger(){
...
}
You should call borger in with():
$borgernotater = PodioBorgerNotat
::orderBy('created_at', 'acs')
->orderBy('id', 'desc')
->with('borger')
->paginate(10);

Related

I can't manually add foreign keys in golang gorm

I am trying to add a foreign key manually in gorm but i get this error
db.Model(&models.Business{}).AddForeignKey undefined (type *gorm.DB has no field or method AddForeignKey)
am using postgres
i have tried
db.Model(&Business{}).AddForeignKey("cust_id", "customers(cust_id)", "CASCADE", "CASCADE")
you can do it with two solution that i know in GORM
#1
when you create model you do it like below:
type Business struct {
Name string
CustomersID int
Customers Customers `gorm:"foreignKey:CustomersID"` // use CustomersID as foreign key
}
type Customers struct {
ID int
Name string
}
#2
every time you want you can add foreign key like below
Client.Exec("ALTER TABLE business ADD FOREIGN KEY (cust_id)" +
"REFERENCES customers (id) ON DELETE CASCADE ON UPDATE CASCADE;")

EntityFramework, problems to create entity with composit key

I have a database first project and the context/entities are automatically generated with Scaffold-DbContext.
One table (Region_User) in the database is a cross reference table between User and Region, it contains only two fields UserId, and RegionId that together is the composit key for the table.
I'm currently trying to add a new Region_User to a user like below:
var userregions = new List<Region_User>();
userregions.Add(new Region_User { UserId = 1, RegionId = 1 });
user.Region_User = userregions;
and then try to save it to the database I get an error like:
{"Entity type 'Region_User' is defined with a 2-part composite key, but 1 values were passed to the 'DbSet.Find' method."}
The generated entity Region_User only contains the fields UserId and RegionId..
How should I do to save a new row in the Region_User table?

Using entity framework to get info from three connected tables

I got products table
->productID - primary
->price
->Quantity
productCategory -table
->prodcatID- primary
->prodId - foreign key
->catID - foreign key
productlanguages - table
->prodID - foreign key
->langID - forein key
->Title
So I use Entity framework and I shoud somehow get all products WITH THEIR TITLE,QUANTITYI PRICE From GIVEN CATEGORY AND FROM GIVEN LANGUAGE.
SO i should somehow combine info from all these three table
so i made my first function to get all products from given category
public List<ProductCategories> GetAllProductsForCategory(int catID)
{
using (OnlineStoreDBContext db = new OnlineStoreDBContext())
{
List<ProductCategories> lst = db.ProuctCategories.Where(x => (x.CategoryID == catID)).ToList();
}
}
So now I have a list with all productID that match this category. But now how to get the data from the other two.
See Loading Related Entities: http://msdn.microsoft.com/en-au/data/jj574232.aspx

Entity Framework: perform a query on a linking table / many to many relationship

I am trying to perform a query using linq to entities to that an entity/table doesn't contain the same values before I update it.
The structure of the database is as follows:
Users User_IPAddresses IPAddresses
----- ---------------- -----------
UserID >------ UserID ------< IPAddressID
User IPAddressID Address
So, the structure of the entity object is as follows
UserSet IPAddressSet
------- >-----< ------------
User IPAddress
All the ID fields are Primary Keys, so the link table (User_IPAddresses) must contain unique rows.
The problem I am having is that I can't get my head around how to check the entities so that I don't violate the unique row constraint on the User_IPAddresses table before I update it.
Any EF gurus out there that can help me?
//returns true if pair exists
public bool CheckIfUserIPPairExists(int ipID, int userID)
{
bool exists
= db.UserSet.Any(user=>user.UserID==userID
&& user.IPAddress.Any(ip=>ip.IPAddressID == ipID));
return exists;
}

ADO.NET Entity : getting data from 3 tables

I have following table structure:
Table: Plant
PlantID: Primary Key
PlantName: String
Table: Party
PartyID: Primary Key
PartyName: String
PlantID: link to Plant table
Table: Customer
PartyID: Primary Key, link to Party
CustomerCode: String
I'd like to have Customer entity object with following fields:
PartyID: Primary Key
CustomerCode: String
PartyName: String
PlantName: String
I am having trouble with PlantName field (which is brought from Plant table
I connected Customer to Party and Party to Plant with associations
However I can not connect Customer to Plant with association ( because it does not have one)
I can not add Plant table to mapping, when I do that - I am getting following error:
Error 3024: Problem in Mapping Fragment starting at line 352: Must specify mapping for all key properties (CustomerSet.PartyID) of the EntitySet CustomerSet
Removing Plant association works.
Any hints or directions very appreciated.
You can get these fields by using the reference path on the Entity Object.
To get the PartyName, use this syntax: Customer.Party.PartyName
To get the PlantName, use this syntax: Customer.Party.Plant.PlantName
You can extend the Customer entity by using the public partial class:
public partial class Customer
{
public string PartyName
{
get { return Party.PartyName; }
set { Party.PartyName = value; }
}
public string PlantName
{
get { return Party.Plant.PlantName; }
set { Party.Plant.PlantName = value; }
}
}
After some research, I came across this thread on MSDN that says you can create a read-only entity, which is enough of a downside to not use it alone, but it gets worse. You will also lose the ability to update all of the models dynamically based on the schema of the database.