I have two tables:
Users (id, name)
Events (id, name, date, user_created_id, user_updated_id (etc...)
How can I make a relationship between the two ids of the Events table with the user id?
user_created_id -> users.id
user_updated_id -> users.id
UPDATE
$table->integer('user_created_id')->unsigned();
$table->integer('user_updated_id')->nullable();
$table->foreign('user_created_id')->references('id')->on('users');
$table->foreign('user_updated_id')->references('id')->on('users');
If your question is how to make a foreign key for those two columns, then here:
$table->unsignedInteger('user_created_id');
$table->unsignedInteger('user_updated_id');
$table->foreign('user_created_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('user_updated_id')->references('id')->on('users')->onDelete('cascade');
If your id column on the users table is bigIncrements then replace the unsignedInteger with unsignedBigInteger
In the Event model, you can define two relationships:
public function user_created(){
return $this->belongsTo('App\User', 'user_created_id');
}
public function user_updated(){
return $this->belongsTo('App\User', 'user_updated_id');
}
In your User model, you can also define the reverse relationships:
public function created_events(){
return $this->hasMany('App\Event', 'user_created_id');
}
public function updated_events(){
return $this->hasMany('App\Event', 'user_updated_id');
}
With these relationshops, you can call $event->user_created to retrieve the App\User linked to the user_created_id (same for the updated version).
With a App\User instance, you can call $user->created_events to get a collection of App\Event (again, it's the same with $user->updated_events).
Related
Here is my problem. I have a table called user and table called skills, also I have a pivot table that connects these two called EmployeeSkill. I am trying to fetch the skills that belong to the user but when i use tinker it returns Base table or view not found: 1146 Table 'pfe_sirh_db.skill_user' doesn't exist (SQL: select skills.*, skill_user.user_id as pivot_user_id, skill_user.skill_id as pivot_skill_id, skill_user.employee_id as pivot_employee_id from skills inner join skill_user on skills.id = skill_user.skill_id where skill_user.user_id = 1)' and am using swagger by the way it returns this "withTimestamps": false
class User extends Authenticatable{
protected $table = "users";
public function skills()
{
return $this->belongsToMany(Skill::class);
}
}
and
class Skill extends Model
{
public function User()
{
return $this->belongsToMany(User::class);
}
}
and the pivot table
class EmployeeSkill extends Model
{
protected $table = "employee_skills";
protected $fillable = [
'employee_id', 'skill_id', 'note'
];
}
Your pivot table should be named skill_user (singular) following the model name they belong to. And you don't need a EmployeeSkill model for this relation to work, you only need the table.
As said in the documentation:
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
And then you should exclude this line:
protected $table = "employee_skills";
change your table name to skill_user
And in your pivot table you should use user_id as a foreign key
You can retrieve all skills from a user by doing this:
$user = User::find(1);
$user->skills();
This will give you all the skills from the user with the id 1
Be aware that you can use any table name and any foreign key name but if you do that you need to specify the names on the relations. So i recommend you doing what i 've told you, since is the standard way
I have two tables user_details and location as below:
user_details
user_id (INTEGER PRIMARY KEY)
......
location
id (INTEGER UNSIGNED PRIMARY KEY)
......
These two tables are related to one another by many to may relationship. Now I am using a pivot table location_user_details as shown below
location_user_details
id (INTEGER UNSIGNED PRIMARY KEY),
user_id (INTEGER FOREIGN KEY REFERENCES use_details.user_id)
location_id (INTEGER FOREIGN KEY REFERENCES location.id)
type (VARCHAR)
The relation code for model UserDetails is as below:
class UserDetails extends Model
{
protected $primaryKey = 'user_id';
........
public function location(){
return $this->belongsToMany(Location::class, 'location_user_details', 'user_id', 'id')->withPivot('type');
}
}
The relation code for model Location is as below:
class Location extends Model
{
......
public function userDetails(){
return $this->belongsToMany(UserDetails::class, 'location_user_details', 'id', 'user_id')->withPivot('type');
}
}
Now in my controller, I am creating the relation after saving both UserDetails and Location object by the following code:
$userDetails->location()->attach($location->id, ['type'=>'HEADQUARTER']);
When the code reaches this line of execution, I get the following exception:
SQLSTATE[HY000]: General error: 1364 Field 'location_id' doesn't have a default value (SQL: insert into location_user_details (id, type, user_id) values (1, HEADQUARTER, 0))
I want to point out to two things that are happening.
The location field is not getting into the query to insert data.
The user_id value is 0 which should be greater than 0 as the data is getting inserted into the user_details table.
Now let me mention here that when I go to the database to look up for data in location and user_details table, I find all the data has been inserted.
Now my question is what has possible gone wrong with this code?
Well at last I have found what went wrong. There is not much documentation on this topic. Actually it lies with the use of the function belongsToMany. The belongsToManyfunction takes up-to 7 parameters. Till now I could decode the first 4 parameters.
The first parameter takes the class of the related model.
The second parameter takes the name of the pivot table in the database.
The third parameter takes the name of the column in the pivot table that references the model on which belongsToMany is called.
The fourth parameter takes the name of the column in the pivot table that references the related model.
So as a result the code for function location in the model UserDetails would look like :
public function location(){
return $this->belongsToMany(Location::class, 'location_user_details', 'user_id', 'location_id')->withPivot('type');
}
And the code for function userDetails in the model Location would look like :
public function userDetails(){
return $this->belongsToMany(UserDetails::class, 'location_user_details', 'location_id', 'user_id')->withPivot('type');
}
I hope this would be helpful to others.
The problem may be in the variable $location, but it is not shown as you create it. Make sure it is a Location Object
I have case like this
table transactions
|id|account_from_id|account_to_id|value|
table account
|id|name|type|
I would like to use eloquent relation from table account to transaction which is it need additional condition, account as from, or account as to, but in one function only relation
this is my code
public function transactions(){
$result = $this->hasOne('App\Transactions','id', 'account_from_id');
if(!is_null($result)){
return $result;
}
return $this->hasOne('App\Transactions','id' 'account_to_id');
}
But it not work as I expected, when account as to, it will return null
The model column has a relation must be define on reference table and column
make each column has a relation on your model
public function account_from(){
return $this->hasOne('App\Transactions','id', 'account_from_id');
}
public function account_to(){
$this->hasOne('App\Transactions','id', 'account_to_id');
}
define the account transaction by the new transaction attribute
public function getTransactionAttribute(){
if(!empty($this->account_from_id)){
return $this->account_from
}else{
return $this->account_to
}
}
I am using backpack CRUD package to create my website project in laravel 5.2
I want to establish a relationship between two tables. First table is called customer and second table is called transaction. Each customer has many transaction(1:N relationship).
Customer table record:
ID Name
123456 xyz
Transaction table record:
ID CustomerID
101010 123456
I know that I have to specify the relation in the customer model. But, how can I display the result of the relationship in CRUD ?
You should have relationships on both the Transaction and the Customer models, so you can do $customer->transactions and $transaction->customer:
class Customer extends Model
{
/**
* Get the comments for the blog post.
*/
public function transactions()
{
return $this->hasMany('App\Transactions', 'CustomerID', 'ID');
}
}
and
class Transaction extends Model
{
/**
* Get the comments for the blog post.
*/
public function customer()
{
return $this->belongsTo('App\Customer', 'CustomerID', 'ID');
}
}
Spend some time in the Eloquent Relationships Documentation. It's really important to understand them if you want to be a Laravel developer.
In order to display the relationship in the CRUD, you can then use Backpack's select column type to display it in the table view and select or select2 field types to display it in the add/edit views. Read the CRUD Example Entity to better understand how that works.
First of all when you are creating migrations for both tables, table which contain Foreign Key (FK) must have field like this:
public function up(){
$table->increments('id');
$table->integer('customerID')->unsigned();
}
After that you are need to call next command into console
php artisan migrate
Next is going next commands:
php arisan backpack:crud customers
php arisan backpack:crud transactions
After that you need to define functions in models which returns values from other tables. Customer models need to have next function
public function transactions(){
return $this->hasMany('Transaction');
}
Transaction model must have next function
public function customer() {
return $this->belongsTo('Customer');
}
Next you must add CRUD field in Customer controller to display
transactions in select box.
$this->crud->addField([
'label' => 'Transactions', // Label for HTML form field
'type' => 'select2', // HTML element which displaying transactions
'name' => 'customerID', // Table column which is FK for Customer table
'entity'=> 'customer', // Function (method) in Customer model which return transactions
'attribute' => 'ID', // Column which user see in select box
'model' => 'Transaction' // Model which contain FK
]);
Hope this helps :)
After you built onetomany relationship with transaction, you can get the results.
$customer=Customer::where(['id'=>'123456'])->with('transaction')
->first();
print_r($customer->Name); // gives the customer name
foreach($customer->transaction as $cid)
{
print_r($cid->CustomerID); // gives the customer id
}
Laravel Relationships Documentation is always helpful. Go through it.
I have a default authentication table user and another table user_profiles
user(id,email,password)
user_profiles(id,first_name,last_name,mobile)
i am connecting these two table using a many-to-many relationship
for this, i added relationship in the both model class- User and UserProfile
// User Model
public function userProfiles()
{
return $this->belongsToMany('App\Models\UserProfile', 'user_user_profile',
'user_profile_id', 'user_id');
}
//UserProfile Model
public function users()
{
return $this->belongsToMany('App\User', 'user_user_profile',
'user_profile_id', 'user_id');
}
and i tried to access the UserProfle details via user table using
$user=\App\User::find(1)->userProfiles()->get();
but not working and also tried
/$user = \App\User::findOrFail(1)->with('userProfiles')->get();
that is also not working , please help to
Get the user_profile table details along with user table
How to access the Pivot table(user_id,user_profile_id) value
How to display these data from multiple tables into a view form?
You have defined the relationship wrong in your User Model: swap user_id and user_profile_id
// User Model
public function userProfiles()
{
return $this->belongsToMany('App\Models\UserProfile', 'user_user_profile',
'user_id' , 'user_profile_id');
}