如何在表中存储外键

时间:2018-04-23 13:02:52

标签: php laravel foreign-keys

我想在我的page_master表中存储一个外键,外键来自business_master表。

这是我的控制器方法:

$page = new Page();
$page->page_name = Input::get('page_name');
$page->page_url  = Input::get('page_url');
$page->business()->business_id;
$page->save();

$resultArray = ['status' => 1, 'message' => 'Page url added!', dataArray' => $page];

我的page_master模型:

protected $table = 'page_master';
protected $fillable = ['business_id','page_url','page_name'];

public function business()
{
    return $this->hasMany('App\Business','business_id','id');
}

这里的外键是business_id,但是当我提出这个请求时,它说:

  

ErrorException:未定义的属性:Illuminate \ Database \ Eloquent \ Relations \ HasMany :: $ business_id

如何将business_id存储为外键?任何帮助将受到高度赞赏!

                    $table->increments('id');
        $table->integer('business_id')->unsigned();
        $table->string('page_url')->unique();
        $table->string('page_name');
        $table->tinyInteger('is_live')->nullable();
        $table->timestamps();

2 个答案:

答案 0 :(得分:1)

实际上,错误就在这一行:

$page->business()->business_id;

您正试图从关系对象中获取属性。

保存模型后,您应该尝试使用attach功能:

$businessId = Input::get('business_id');
$page->business()->attach($businessId);

关于外键问题,您需要在迁移文件中使用foreign:

$table->foreign('business_id')->references('id')->on('business_master');

看看这里:https://laravel.com/docs/5.6/migrations#foreign-key-constraints

答案 1 :(得分:0)

此代码应该适合您。

$page = new Page();
$page->page_name = Input::get('page_name');
$page->page_url  = Input::get('page_url');
$page->business_id = $businessId;
$page->save();

此代码行生成错误 $ page-> business() - > business_id; 实际上用于检索关系数据。

人们还使用附加 $ page-> business() - > attach($ businessId); 但我更喜欢简单。因此,我始终坚持这个惯例 $ page-> business_id = $ businessId;

在迁移中添加外键:

$table->increments('id');
$table->integer('business_id')->unsigned();
$table->string('page_url')->unique();
$table->string('page_name');
$table->tinyInteger('is_live')->nullable();
$table->foreign('business_id')->references('id')->on('business_master');
$table->timestamps();

如果使用foreign_key,则必须考虑级联操作。要了解有关外来约束的更多信息,请查看document