简体   繁体   English

两个模型之间的Laravel关系

[英]Laravel Relationships Between Two Models

I am struggling with working with relationships right now and would like some help as for how to make this relationship work. 我现在正努力处理各种关系,并且希望获得一些有关如何使这种关系正常工作的帮助。 I am using Laravel. 我正在使用Laravel。

Lets say you have a staff model that looks like so: 假设您有一个员工模型,如下所示:

Staff.php Staff.php

class Staff extends \Eloquent {
    protected $fillable = [];

    public function status()
    {
        return $this->belongsTo('Staff_status');
    }
}

The database table for the staff is as follows: 工作人员的数据库表如下:

Table Name: staff
Fields: id, staffer_name, status_id

You also have a staff status model represented below: 您还具有以下所示的员工身份模型:

Staff_statuses.php Staff_statuses.php

class Staff_status extends Eloquent {

    public function staff()
    {
        return $this->hasMany('Staff');
    } 

}

You also have a staff database table like so: 您也有一个职员数据库表,如下所示:

Table Name: staff_statuses
Fields: id, status_name

However when I try and load the staff controller index method it says class Staff_status is not found. 但是,当我尝试加载人员控制器索引方法时,它说未找到类Staff_status。

Any idea why? 知道为什么吗?

You have used Staff_statuses.php as the name of your model but you are using Staff_status in the class name and thus you are calling it using Staff_status from your controller as well. 您已经使用Staff_statuses.php作为model的名称,但是在类名中使用了Staff_status ,因此您也可以从控制器中使用Staff_status对其进行调用。 This is the problem. 这就是问题。

Change the file name to match the class name . 更改文件名以匹配class name For example, use something like this: 例如,使用以下内容:

// StaffStatus.php
class StaffStatus extends Eloquent{

    protected $table = 'staff_statuses';

    public function staff()
    {
        return $this->hasMany('Staff');
    } 
}

// Staff.php
class Staff extends Eloquent {

    protected $table = 'staff';

    protected $fillable = [];

    public function status()
    {
        return $this->belongsTo('StaffStatus');
    }
}

In the controller you may use something like this: controller您可以使用以下命令:

$staffStatus = StaffStatus::all();
$staff = Staff::all();

namespace App; 命名空间应用;

use Illuminate\\Database\\Eloquent\\Model; 使用Illuminate \\ Database \\ Eloquent \\ Model;

class Photo extends Model { 类照片扩展模型{

public function imageable()
{
    return $this->morphTo();
}

} }

class Staff extends Model { 班级员工扩展模型{

public function photos()
{
    return $this->morphMany('App\Photo', 'imageable');
}

} }

class Product extends Model { 类产品扩展模型{

public function photos()
{
    return $this->morphMany('App\Photo', 'imageable');
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM