laravel 5.4 many to many relationship - database

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

Related

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);

How to join two database table in sql query for cakephp 3.6.7

can anyone tell me to join two tables from database
my php query is :
SELECT * FROM `users` INNER JOIN registration ON users.id=registration.id WHERE users.id='7'
can anyone convert to Cakaphp 3.6.7
thanks & regards,
Darshan
First of all you should use plural name for your model Registration. It should be Registrations.
You can use association for the same in Cakephp.
First define your association in /src/Model/Table/UsersTable.php file.
class UsersTable extends Table
{
public function initialize(array $config)
{
$this->hasOne('Registrations')->setJoinType('INNER');;
}
}
Then query like this
$this->Users->find('all')->contain('Registrations')->where(['Users.id => 7]);
Reference: https://book.cakephp.org/3.0/en/orm/associations.html

ASP MVC 5 EF 6 - Insert into Multiple Tables

I have an existing database, from which I have built a shell web-app using VS2013 and EF6, but I have run into a few problems.
My database has the following tables, for example:
Table: Customer (Id, First, Last, Date)
Table: Assets (Id, CustID)
Table: Orders (Id, AssetId, CustID)
When the EF created the shell webapp for me (which has awesome) it gave me the following method, for example, to create a new Customer:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Id, First, Last, Date")] Customer customer)
....
return View(customer)
In my database I have a one Customer to many orders and assets, but I don't understand how to use this relationship during a Create operation, or any other.
My question -- How do I "Create" a new Customer when this operation needs to span multiple tables? For example, when the "Create Customer" form is filled out, you would add one or more Assets and/or Orders.
Should I use a stored procedure to do multiple inserts across three different tables? Or can I make a change to the database that will let me use all the EF magic?
Thanks for your help!
You can use a view model that contains all three classes.
public class CreateCustomerViewModel
{
public Customer Customer { get; set; }
public ICollection<Asset> Assets { get; set; }
public ICollection<Order> Orders { get; set; }
}
Your [HttpGet] action method will pass this view model as the model instead of a Customer.
[HttpGet]
public ActionResult Create()
{
CreateCustomerViewModel model = new CreateCustomerViewModel();
return View(model);
}
Your [HttpPost] action method will take the CreateCustomerViewModel as a parameter:
[HttpPost]
public ActionResult Create(CreateCustomerViewModel model)
{
// Create the Customer with the necessary Assets and Orders and save
}
If you're classes and relationships are configured properly, adding the appropriate Assets and Orders to the navigation properties on your Customer entity should trigger EF to automatically insert the assets and orders into the appropriate tables when you insert the Customer.

How to join tables using Hibernate Criteria Query

I have a School table and Classroom table which has foreign key to School table. I want to get classrooms that capaties are 40 and school name is "example". Here is my generic getAll method. I want to modify this method to join 2 tables. The problem is the method still must remains generic.
public <T> List<T> getAll(T genericEntity) {
Criteria criteria = getCurrentSession().createCriteria(genericEntity.getClass());
criteria.add(Example.create(genericEntity));
return criteria.list();
}
You should add both objects to the parameter list:
public <T,U> List<T> getAll(T genericEntity1, U genericEntity2) {
Criteria criteria = getCurrentSession()
.createCriteria(genericEntity1.getClass()).add(Example.create(genericEntity1))
.createCriteria(genericEntity2.getClass()).add(Example.create(genericEntity2));
return criteria.list();
}
You can call it the following way:
getAll(classroom, school);

How to design a table which have many-to-many relationship with itself?

For example, A Users entity has a friends property, how can I design this friends property, in my thought there are 2 ways:
friends property is a String with all usernames splitted by "," in this way it's hard to read and modify.
friends property is a Set like Set<Users>, but in this way I don't know how to write in entities?
Anyone knows the best practise?
This is covered Enterprise Model Patterns by Hay.
A party represents a person (or an organization):
Party
id
name
A party can have a relationship to another party, over a time period:
PartyRelationship
fromPartyId
toPartyId
fromDate
toDate nullable
A basic diagram:
Party -< PartyRelationship >- Party
Sample SQL:
insert into party values (1, 'Jerry');
insert into party values (2, 'Neil');
insert into partyRelationship values (1, 2, getDate(), null);
If a User can have multiple friends you could annotate your User entity like this:
#Entity
public class User
{
#Id
private Long id;
private String name;
#ManyToMany
#JoinTable(
name = "user_friends",
joinColumns =
{ #JoinColumn(
name = "user_id") },
inverseJoinColumns =
{ #JoinColumn(
name = "friend_id") })
private Set<User> friends;
}
This way a table will get created for User and a join table for the relationship between Users. The User table will have 2 columns, 'id' and 'name'. The user_friend table will have 2 columns, 'user_id' and 'friend_id'. The columns in user_friend are both foreign keys to the User table.

Resources