Laravel 5.2 : Relationship - please advise - laravel-5

User Model
| Field | Type
+-----------------+-----------------
id | int(10) unsigned | NO
name | varchar(255) | NO
email | varchar(255) | NO
Club Model
Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+-------------------+-------+
| id | int(10) unsigned | NO | | NULL | |
| user_id | int(10) unsigned | NO | | NULL | |
| name | varchar(255) | NO | | NULL | |
Club member Model
+------------+------------------+------
Field | Type
id | int(11)
club_id | int(10)
user_id | int(10)
status | varchar(20)
How to make relationship using laravel?
I assume that User has many club .
in User Model
`public function clubs()
{
return $this->hasMany('App\Club');
}`
Club has many members(users). I created ClubMember model
how to declare the relation in clubMember model? and **club member belongs to club and user **

Looks like a many to many relationship to me. Your "Club member Model" table is the pivot table.
You can add this relation to your user model:
public function clubs()
{
return $this->belongsToMany('App\Club', 'PIVOT TABLE NAME');
}
and this to your club model:
public function users()
{
return $this->belongsToMany('App\User', 'PIVOT TABLE NAME');
}
Change PIVOT TABLE NAME to the name of your table. Laravel assumes that it is named "club_user". If you name it like this, you dont need to add the second parameter.
Check the Laravel documentation for more information on many to many relationships.

Related

How to describe a schema for many-to-many GrhapQl relationships with custom properties?

How to describe a schema for many-to-many GrhapQl relationships with custom properties?
Hi guys! I have the following tables:
+-------------+--------------+----------------------------+
| Product |
+-------------+--------------+----------------------------+
| id | int(11) | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(255) | |
+-------------+--------------+----------------------------+
+-------------+--------------+----------------------------+
| Nutrient |
+-------------+--------------+----------------------------+
| id | int(11) | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(255) | |
| unit | varchar(255) | |
| alias | varchar(255) | |
+-------------+--------------+----------------------------+
+-------------+--------------+----------------------------+
| Product_To_Nutrient |
+-------------+--------------+----------------------------+
| nutrientId | int(11) | PRIMARY KEY FOREIGN KEY |
| productId | int(11) | PRIMARY KEY FOREIGN KEY |
| amount | int(11) | |
+-------------+--------------+----------------------------+
To get nutrients, I use dataloader.
How can I describe my schema so that I can run the following query and get the AMOUNT for each nutrient? Or maybe I need to rebuild my database, if so, which architecture would be optimal? Thank you in advance for your advice :)
query Product {
getProducts {
id,
name,
nutrients: {
name,
unit,
alias,
AMOUNT
}
}
My stack: TypeOrm, TypeGraphQL, MicroOrm, NodeJs.
rename the Product_To_Nutrient table to ingredients (just for convenience)
and move the unit property from the nutritient to your ingredient as it's important to know the quantity in units. (In the current situation, if you would ever have to update the unit, you also have to update all ingredients using that nutritient.
Querying with GraphQL, you'll have to do through the ingredients
query Product {
getProducts {
id,
name,
ingredients: {
nutrient: {
id,
name,
alias
},
quantity,
unit
}
}
}
To load the ingredient, when querying the products, you can make it an 'eager' relationship.
Use the Dataloader to load all the nutrients linked to the ingredient.

laravel eloquent error , I can not get created_at use groupBy method

I am trying to get max value and create at date with groupBy method.
But when I put the created_at column, I got an error.
$rankings = Ranking
::select(DB::raw('MAX(rankings.percentage_correct_answer) as percentage_correct_answer, rankings.user_id,rankings.created_at'))
->groupBy('rankings.user_id')
->get();
errors:
SQLSTATE[42000]: Syntax error or access violation: 1055 'app.rankings.created_at' isn't in GROUP BY (SQL: select MAX(rankings.percentage_correct_answer) as percentage_correct_answer, rankings.user_id,rankings.created_at from rankings where rankings.deleted_at is null group by rankings.user_id)
However, I did fine by pulling out the created_at column. Why?
And I want to get the created_at column, what should I do?
No error this code.
$rankings = Ranking
::select(DB::raw('MAX(rankings.percentage_correct_answer) as percentage_correct_answer, rankings.user_id'))
->groupBy('rankings.user_id')
->get();
Model code:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Ranking extends Model
{
use SoftDeletes;
protected $table = 'rankings';
protected $fillable = [
'user_id','percentage_correct_answer'
];
}
rankings table description:
+---------------------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| user_id | bigint(20) unsigned | NO | | NULL | |
| percentage_correct_answer | int(11) | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| deleted_at | timestamp | YES | | NULL | |
+---------------------------+---------------------+------+-----+---------+----------------+
Thanks Tharaka!
I tried add database config in config/database.php:
'mysql' => [
....
'strict' => false,
//'strict' => true,
],
Then it works.
I referred to this question.
GroupBy Error in Laravel Eloquent Builder
But I don't really understand the cause of the error.

change of model but database not changed accordingly

I'm new to golang.
Here's my code:
//main.go
type Project struct {
gorm.Model
Name string
}
type Log struct {
gorm.Model
Project Project
User User
CheckPoint string
Status uint
}
type User struct {
gorm.Model
Name string
Password string
}
//...
db.AutoMigrate(&Project{}, &Log{}, &User{})
I want to:
Log.Project ==> Project.ID
Log.User ==> User.ID
But in the database logs table, it's:
desc logs;
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
| deleted_at | datetime | YES | MUL | NULL | |
| check_point | varchar(255) | YES | | NULL | |
| status | int(10) unsigned | YES | | NULL | |
+-------------+------------------+------+-----+---------+----------------+
I can't see the ProjectID nor the UserID.
Any guidance?
Thank you in advance.
edit on 0825:
Hi there,
Maybe I need to explain myself firstly.
I need three tables: projects, users, logs.
In the logs, it records which user did what to which project.
I changed a little:
type Project struct {
gorm.Model
Name string
}
type User struct {
gorm.Model
Name string
Password string
}
type Log struct {
gorm.Model
ProjectID uint
UserID uint
CheckPoint string // ie: what to record
Status uint // ie: record's status
}
...
db.Debug().Model(&Log{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
db.Debug().Model(&Log{}).AddForeignKey("project_id", "projects(id)", "RESTRICT", "RESTRICT")
When I ran the code,
Error 1452: Cannot add or update a child row: a foreign key constraint fails (`test`.`logs`, CONSTRAINT `logs_project_id_projects_id_foreign` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`))
Error 1452: Cannot add or update a child row: a foreign key constraint fails (`test`.`#sql-1a0f3_18`, CONSTRAINT `logs_user_id_users_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))
I'm lost.
You are using a has one relationship so the foreign key will be in the owned models (Project & User tables should have a log_id) column. Maybe what you want is a belongs to relation.

Relation between 3 Models in Laravel 5.1 ("like many-to-many-through")

I'm developing a simple Schools management app for an exam and have so far built a simple Many-To-Many relation between a School model and the Field model and of course a pivot table.
Now I want to relate my User model to them so that I can query for example
{user} is studying {field_of_study} at {school}
At the end I want to be able to query for example
how many users are studying at School XY or,
how many are studying Field Z or,
how many are studying Field Z at School XY.
Furthermore I want to be able to query all fields of study for a given school and vice versa.
My tables so far
Table users:
+------------+---------------------+
| Field | Type |
+------------+---------------------+
| id | bigint(20) unsigned |
| username | varchar(60) |
| password | varchar(60) |
+------------+---------------------+
Table schools:
+------------+---------------------+
| Field | Type |
+------------+---------------------+
| id | bigint(20) unsigned |
| name | varchar(60) |
+------------+---------------------+
Table fields:
+------------+---------------------+
| Field | Type |
+------------+---------------------+
| id | bigint(20) unsigned |
| name | varchar(60) |
+------------+---------------------+
Table schools_pivot:
+------------+---------------------+
| Field | Type |
+------------+---------------------+
| id | bigint(20) unsigned |
| school_id | bigint(20) |
| field_id | bigint(20) |
+------------+---------------------+
Unfortunatly I absolutly have no clue how to relate three Eloquent models in such a way and couldn't find any thing on the web (I probably searched for the wrong terms).
I'm pretty new to Laravel and Eloquent, so please be kind with me ;)
it's better to define relationship between two table and then alternately the other one.you can read this artical. maybe it will help you three-way-pivot-table-in-eloquent

Laravel 4 BelongsToMany sync() method doesn't work properly

I have problem when using sync() method. Please help me out here.
I have three tables as below.
Table: tbl_roles
+----------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+------------------+------+-----+---------+----------------+
| id_role | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(60) | NO | UNI | NULL | |
| description | text | YES | | NULL | |
+----------------+------------------+------+-----+---------+----------------+
Table: tbl_permissions
+----------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+------------------+------+-----+---------+----------------+
| id_permission | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| description | text | YES | | NULL | |
+----------------+------------------+------+-----+---------+----------------+
Table: tbl_link_roles_permissions
+---------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------+------+-----+---------+-------+
| id_role | int(10) unsigned | NO | MUL | NULL | |
| id_permission | int(10) unsigned | NO | MUL | NULL | |
+---------------+------------------+------+-----+---------+-------+
I have created many to many relationship between roles and permissions models.
Role model:
class Role extends Eloquent
{
/**
* Permissions
*/
public function permissions()
{
return $this->belongsToMany('Permission', 'tbl_link_roles_permissions', 'id_role', 'id_role');
}
}
Permission model:
class Permission extends Eloquent
{
/**
* Roles
*/
public function roles()
{
return $this->belongsToMany('Role', 'tbl_link_roles_permissions', 'id_permission', 'id_permission');
}
}
When I run the following code to sync roles' permissions. It give me an Integrity constraint violation error.
The Code:
$role = Role::find($id_role);
$permissions = Input::get('role_permissions');
/*
* Permissions array is like array('1','2','3')
* So I convert the value to integer.
*/
$parameters = array();
foreach($permissions as $permission) {
$parameters[] = intval($permission);
}
$role->permissions()->sync($parameters);
According to the error message, I found the SQL query is not correct.
Error meesage:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row:
a foreign key constraint fails (`quidz_host_laravel`.`tbl_link_roles_permissions`,
CONSTRAINT `tbl_link_roles_permissions_id_permission_foreign` FOREIGN KEY
(`id_permission`) REFERENCES `tbl_permissions` (`id_permission`)) (SQL: insert into
`tbl_link_roles_permissions` (`id_role`) values (?)) (Bindings: array ( 0 => 1, ))
It only inserts id_role. This is not what I want. Can anyone tell me what I did wrong?
Thanks a lot.
I have solved my problem. It's caused by passing wrong parameters when building the relationships.
The relationship should be like the code below:
class Role extends Eloquent
{
/**
* Permissions
*/
public function permissions()
{
return $this->belongsToMany('Permission', 'tbl_link_roles_permissions', 'id_role', 'id_permission');
}
}
class Permission extends Eloquent
{
/**
* Roles
*/
public function roles()
{
return $this->belongsToMany('Role', 'tbl_link_roles_permissions', 'id_permission', 'id_role');
}
}

Resources