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
CodePudding user response:
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');
}
}