在laravel中迈出第一步,然后撞墙。
我有两个实体:
Schema::create('addresses', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->increments('id');
$table->string('street');
(...)
});
Schema::table('company', function($table) {
$table->foreign('addressid')
->references('id')->on('addresses')
->onDelete('cascade');
});
和
class Address extends Model {
public function shipyard() {
return $this->belongsTo('App\Company', 'addressid');
}
}
class Company extends Model {
public function address() {
return $this->hasOne('App\Address', 'id', 'addressid');
}
}
模型
Route::post('/company', function (Request $request) {
(...validation...)
$company = new Company();
$company->name = $request->name;
$address = new Address();
$address->street = $request->street;
(...)
$company->address()->save($address);
$company->save();
return redirect('/');
});
当我想在DB中创建这些实体时,我在HTML中使用一个表单来收集所有数据。然后我发布请求并执行:
{{1}}
结果我在DB中有两个实体,但是" addressid" field为null。为什么呢?
答案 0 :(得分:1)
更改公司关系(您可以删除的地址中的关系):
Route::post('/company', function (Request $request) {
(...validation...)
$company = new Company();
$company->name = $request->name;
$address = new Address();
$address->street = $request->street;
(...)
$address->save();
$company->address()->associate($address);
$company->save();
return redirect('/');
});
保存代码:
SELECT DISTINCT
customer.first_name
FROM
rental,
customer
WHERE
rental.customer_id = customer.customer_id
GROUP BY
rental.rental_id
HAVING
(
rental.return_date - rental.rental_date
) =(
SELECT
MAX(countRental)
FROM
(
SELECT
(
rental.return_date - rental.rental_date
) AS countRental
FROM
rental,
customer
GROUP BY
rental.rental_id
) AS t1
)
答案 1 :(得分:0)
class Address extends Model {
// Added fillable array for mass assigment
protected $fillable = ['street'];
public function shipyard() {
return $this->belongsTo('App\Company', 'addressid');
}
}
class Company extends Model {
// Added fillable for mass assignment
protected $fillable = ['name','addressid'];
// The second argument for the hasOne takes a foreign key not a primary key
public function address() {
return $this->hasOne('App\Address', 'addressid');
}
}
$company = new Company();
$company->name = $request->name;
$company->save();
$company->address()->create($request->street)