I am using laravel framework to develop apis.we are not using migration files instead of that one we are hardcoding table name in models,is there any chance i can use relationships without migrations.
Let’s consider user hasMany books in this scenario how can i relate them in model.
Users table
u_id ,u_name ,u_role
books table
b_id, b_uid ,b_name
Note:- u_id is related to b_uid
Migrations and models are not related in any way. Migrations are needed to make changes to the database structure. If you change the database structure in any other way, this should not interfere with the use of models and relationships
class Book extends Model
{
protected $primaryKey = 'b_id';
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'b_uid', 'u_id');
}
}
class User extends Model
{
protected $primaryKey = 'u_id';
public function books(): HasMany
{
return $this->hasMany(Book::class, 'b_uid', 'u_id');
}
}
Related
I have 2 models: User and Role.
A user can have many roles.
A role can have many users.
I have a custom pivot model between these 2 models. This custom pivot model only exists because it uses a trait that listens/logs for events such as created, updated, deleted.
Let's say I have a role called moderator. When I attach() (or detach()) that role to 5 users, it does successfully fire 5 created (or deleted) events for the pivot table.
$roleModerator->users()->attach($anArrayOfFiveUsersHere);
So far so good.
My problem is the following: when I delete the moderator role itself, it does delete all pivot rows associated to the role, but it does not fire any deleted event for each deleted pivot rows.
Expected behavior: I want Laravel to fire deleted events for each rows it deletes in the pivot table when I ask it to delete the role.
Environment: PHP 7.3 / Laravel 6
One weird thing I noticed, if I add this to my Role model :
public static function boot()
{
parent::boot();
static::deleting(function (self $model)
{
//$model->users()->detach(); // <-- this fails firing deleted events.
//MyCustomPivot::query()->where('role_id', $model->id)->get()->each->delete(); // <-- this fails firing deleted events.
$model->users()->sync([]); // <--- this works!
});
}
sync([]) will work great and fire as many deleted events as it deletes pivot rows.
but detach(), although it accomplishes the same thing, won't fire any deleted event. Why is that? They are both from InteractisWithPivotTable.php and sync() does even call detach() itself!
Not 100% sure it's applicable to your situation, but according to this issue on Github, you need to do some setup in your models.
First, make sure you have a primary key column in your table and defined on your pivot model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class MyCustomPivot extends Pivot
{
public $primaryKey = "id";
public $incrementing = true;
}
Second, make sure you include your custom pivot model in your relationships.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class)
->using(MyCustomPivot::class)
->withPivot('id');
}
}
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class)
->using(MyCustomPivot::class)
->withPivot('id');
}
}
I try load relations like:
return $task->load('users', 'creator', 'attachments', 'messages.creator');
Relation 'users' many to many with some fields
user
id
name
...
task
id
name
...
task_user
user_id
task_id
task_status_id
my pivot model
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class TaskUser extends Pivot
{
public $incrementing = true;
public function status()
{
return $this->hasOne(TaskStatus::class);
}
}
How to correctly load 'status' relation?
If Laravel provided a way to pass Closures in pivots it wouldn't be hard at all however there are 2 solutions at the moment to load pivot relationships
1. Lazy eager load everything.
# App\Task.php
public function users()
{
return $this->belongsToMany(App\User::class)->using(App\TaskUser::class)->withPivot('task_status_id');
}
$task->load('users', ...);
$task->users->each(function ($user) {
$user->pivot->load('status');
});
The problem: This makes a query for each User related to Task. Unless you paginate your results, it's the classic N+1 problem.
2. Use hasMany and belongsTo instead.
Define $user->tasks_user relationship (User hasMany TaskUser)
Define $task->tasks_user relationship (Task hasMany TaskUser)
Define the inverse (TaskUser belongsTo User, TaskUser belongsTo Task)
Define the last task_user relationship (TaskUser hasOne TaskStatus) (looks like a belongsTo to me though)
Load relationships $task->load('task_user.user', 'task_user.status')
There's no real problem with this implementation besides not using belongsToMany.
I'm kind of new to the Eloquent (Pivot / Intermediate Tables) idea.
I am using Laravel 5.3 and the docs are making a little sense, but not enough. Unfortunatley!
I have a few scenarios that I'd like to try get data from...
I have the following DB Tables
Companies
Company_Offers
Offers
Company_Attributes
Attributes
In my scenarios the following is said of these DB Tables...
A company can have many offers
A company can have many attributes
An Offer can be associated with many companies
An attribute can be associated with many companies
I have created the 5 models to correspond to the 5 DB Tables.
I am trying to work out, How I get these relationships into my models?
Thank You!
You want to use the belongsToMany relationship. For example:
class Company extends Model
{
public function offers()
{
return $this->belongsToMany(App\Offer::class);
}
}
If you have setup your pivot table with company_id and offer_id this relationship will work automatically, and a pivot table of company_offer (singular version of model name in alphabetical order). If you didn't follow the naming convention you can specify the pivot table and foreign keys like so:
return $this->belongsToMany('App\Offer', 'Company_Offers', 'Company_ID', 'Offer_ID');
Actually in laravel you don't have to create models for pivot tables. So you are down to three models that will look more less like this:
<?php
/* /app/Company.php */
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
/**
* The offers that belong to the company.
*/
public function offers()
{
return $this->belongsToMany('App\Offer');
}
/**
* The attributes that belong to the user.
*/
public function attributes()
{
return $this->belongsToMany('App\Attribute');
}
}
<?php
/* /app/Offer.php */
namespace App;
use Illuminate\Database\Eloquent\Model;
class Offer extends Model
{
public function companies()
{
return $this->belongsToMany('App\Company');
}
}
<?php
/* /app/Attribute.php */
namespace App;
use Illuminate\Database\Eloquent\Model;
class Attribute extends Model
{
public function companies()
{
return $this->belongsToMany('App\Company');
}
}
More on how to use it to select or update those relations you can find here:
https://laravel.com/docs/5.3/eloquent-relationships#many-to-many
Can any body tell me what is the main difference between
the BelongsTo and HasOne relationship in eloquent.
The main difference is which side of the relation holds relationship's foreign key. The model that calls $this->belongsTo() is the owned model in one-to-one and many-to-one relationships and holds the key of the owning model.
Example one-to-one relationship:
class User extends Model {
public function car() {
// user has at maximum one car,
// so $user->car will return a single model
return $this->hasOne('Car');
}
}
class Car extends Model {
public function owner() {
// cars table has owner_id field that stores id of related user model
return $this->belongsTo('User');
}
}
Example one-to-many relationship:
class User extends Model {
public function phoneNumbers() {
// user can have multiple phone numbers,
// so $user->phoneNumbers will return a collection of models
return $this->hasMany('PhoneNumber');
}
}
class PhoneNumber extends Model {
public function owner() {
// phone_numbers table has owner_id field that stores id of related user model
return $this->belongsTo('User');
}
}
BelongsTo is a inverse of HasOne.
We can define the inverse of a hasOne relationship using the belongsTo method.
Take simple example with User and Phone models.
I'm giving hasOne relation from User to Phone.
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
Using this relation, I'm able to get Phone model data using User model.
But it is not possible with Inverse process using HasOne. Like Access User model using Phone model.
If I want to access User model using Phone, then it is necessary to add BelongsTo in Phone model.
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
You can refer this link for more detail.
One-to-one relationship: You, as a User, can have one (hasOne) Profile. And of course the inverse also applies. Profile (belongsTo) a User. A user can't have more than one profile and a profile can't belong to multiple users.
If you want to make One TO one relationship between two table then first you have to make "hasOne" Relation and If you want to make inversely table relationship then you make " "Belongs to"... IT is a simple difference between HasOne and Belongs to the relationship if you want to know about this
One To Many (Inverse)
Now that we can access all of a post's comments, let's define a relationship to allow a comment to access its parent post. To define the inverse of a hasMany relationship, define a relationship function on the child model which calls the belongsTo method:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
Here you can see a good example and see what the difference is between BelongsTo and HasOne relationship in eloquent.
Eloquent Relationships Cheat Sheet by Mahmoud Zalt https://link.medium.com/9lj9BAG8lR
I have the Project model and the Contract model. When i execute Project:all() it gets me only the projects without the contract, same for contract. I tried to dd() inside contract and doesn't do anything, like is never executed. I also tried with App\ prefix and without.
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $table = 'project';
public function contract() {
return $this->belongsTo('Contract');
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contract extends Model
{
protected $table = 'contract';
public function project() {
return $this->hasMany('Project', 'ContractID', 'ContractID');
}
}
I try to retrieve them like this:
$projects = Project::all()->take(10);
You have a few problems here.
Project::all()->take(10);
This only returns a collection of projects. You havent specified that you want the contracts also.
$projects = Project::with('contract')->get();
In your belongsTo - You havent specified the column that the table should join on. You need to do this, because you have not used a standard id for primary key and contract_id for foreign key.
unrelated to specific question, but your relationship in contract model is also wrong.
public function project() {
return $this->hasMany('Project', 'ContractID', 'ContractID');
}
If one contract has many projects, then your public function project() should be public function projects();
Finally - Why are you using non-standard table / column naming conventions? What's wrong with contract_id? Are you aware that mysql is non-case sensitive? Also the project table could be renamed projects and the contract table could be renamed contracts. It will make you writing your eloquent relations much easier and makes more sense!
If you used standard naming conventions, then you could just do this to declare your model relations.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contract extends Model
{
public function projects() {
return $this->hasMany('Project');
}
}
Notice you dont need to specify the table name in the model, or how the table is related to the Project.