向Eloquent模型添加字段


Add field to an Eloquent model

所以我有两个Laravel/Eloquent模型,我想在其中一个模型上再添加一个字段。

模型"Car"从表"cars"中获取数据,并具有字段"id"、"Model"、"color"answers"price"。模型"Person"具有字段"id"、"name"answers"car_id",这是"cars"表中的外键。我希望模型"Person"有一个名为"car"的字段,该字段将包含"car"模型中的汽车模型,具体取决于现有的car_id。我试过这样的东西:

use App'Models'Car;
    class Person extends Model {
        protected $car = array(Car::find($this->car_id));
    }

但没有成功(错误如"语法错误,意外"(",应为")")。解决方案是什么?谢谢

您需要首先定义一对多关系。然后为此人获取车型:

$carModel = Person::find($personId)->car->model;

看看Eloquent Relationships。您正在尝试创建CarPerson模型之间的关系。一个人是否可以拥有一辆或多辆汽车,这取决于你。我建议你让一个人拥有多辆车。

因此,Person模型应该知道它有多辆车:

class Person extends Model
{
    public function cars()
    {
        return $this->hasMany(App'Car::class);
    }
}

汽车属于一个人,所以模型应该知道:

class Car extends Model
{
    public function person()
    {
        return $this->belongsTo(App'Person::class);
    }
}

当然,在创建表时,应该将字段person_id添加到CARS表中。

好吧,我需要的是:

protected $appends = ['car'];
    public function getTypeAttribute($car)
    {
        return Car::find($this->car_id)->model;
    }

这一切都是关于序列化和"受保护的$appends",谢谢大家:)

事情并非如此。

此人可以拥有一辆(或多辆)汽车。让我们假设每个人在您的数据库中都有一辆车,您的汽车表应该有一个可以为null的person_id列,并将其添加到您的用户模型中

public function car() {
        return $this->hasOne('App'Role');
}

现在你可以得到这个人和他的汽车信息,就像这个

User::where('id',$id)->with('car')->get();

我希望你在这里明白这一点