Home > front end >  laravel eloquent migrations
laravel eloquent migrations

Time:05-20

In laravel eloquent relationship, is it still necessary to make migration even though there's an existing database? beginners here.

I create a one-to-one eloquent relationship inside my model to get the specific column from another table's record and fetch to the datatable, but it did not work.

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Directorystatus extends Model
{
    use HasFactory;

    protected $table = 'user_status';
    protected $fillable = ['status_id' , 'status_xtitle'];

    public function userbasic() {
        return $this->belongsTo(directorybasic::class,'user_xusern','status_xuser');
    }
}

class Directoryuser extends Model
{
    use HasFactory;

    protected $table = 'user_basic';
    protected $primaryKey = 'user_id';
    protected $fillable = ['user_id' , 'user_xusern' , 'user_xfirtname' ,'user_xmiddlename','user_xlastname'];

    public function userstatus() {
        return $this->hasOne(directorystatus::class,'user_xusern','status_xuser');
    }
}

CodePudding user response:

No. Migrations are not necessary. Defining relationships on both sides is also not necessary, if you don't need them both. (You can have only belongsTo, without having hasOne or hasMany in the opposite model.)

First, make sure you are using the right object (Directorystatus::class / Directoryuser:class - I see they're not capitalized in your code). The next param is the foreign key, meaning the column which points to a model's primary key. The third param is optional and is used only if the primary key is not id.

For example if you have a column status_xuser in the table user_status, which contains a user_id from user_basic table, you should define it like this:

public function userbasic() {
    return $this->belongsTo(Directoryuser::class,'status_xuser','user_id');
}

And in order to use this relationship, when you retrieve a model from the db, for example, you should call on it the same way your relationship function is named.

$status = Directorystatus::find(1);
$user = $status->userbasic();

I would also suggest you name your classes in camelCase, because it's the accepted practice (in Laravel especially).

  • Related