Laravel关系不起作用

时间:2015-07-06 23:21:37

标签: php laravel laravel-5

我正在尝试在两个Eloquent模型User和Company之间建立关系。用户是标准型号,标配新的Laravel项目,公司是使用Artisan创建的模型。

我已按以下方式设置关系:

用户类:

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public function companies() {
        return $this->hasMany('App\Company');
    }
}

公司类:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;

class Company extends Model
{

    protected $table = 'companies';

    public function owning_user() {
        return $this->belongsTo('App\User', 'id');
    }


}

我正在尝试使用DatabaseSeeder类中的以下代码创建模型(它也在修补程序中执行此操作):

$user = new \App\User();
$user->name = "Josh Pennington";
$user->email = 'xxx@xxx.xxx';
$user->password = bcrypt('xxx');
$user->save();

$company = new \App\Company();
$company->name = "Business Name";
$company->default_tax_rate = 6.5;
$company->owning_user = $user;
$company->save();

但是,我收到以下错误:

[Illuminate\Database\QueryException]                                                                                                                 
  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'owning_user' in 'field list' (SQL: insert into `companies` (`name`, `default_tax_rate`, `ow  
  ning_user`, `updated_at`, `created_at`) values (Business Name, 6.5, {"name":"Josh Pennington","email":"xxx@xxx.xxx","updated_at":"2015-07-06 23:09:  
  11","created_at":"2015-07-06 23:09:11","id":1}, 2015-07-06 23:09:11, 2015-07-06 23:09:11)) 

正如您所看到的,它认为owning_user是列名,当它实际上应该是user_id作为列名时,它不应该在查询中给出对象的JSON版本。我做了什么明显的错误?

1 个答案:

答案 0 :(得分:3)

您可以执行此操作并将外键提供给&#34; user_id&#34;公司类的财产:

$company = new \App\Company();
$company->name = "Business Name";
$company->default_tax_rate = 6.5;
$company->user_id = $user->id;
$company->save();

或者您可以使用公司类的eloquent owning_user方法,并将其传递给User实例。

$company = new \App\Company();
$company->name = "Business Name";
$company->default_tax_rate = 6.5;
$company->owning_user()->associate($user);
$company->save();