【发布时间】:2017-03-27 06:50:38
【问题描述】:
您好,我正在尝试创建一对多关系。用户表中的一个用户可以拥有多个公司,而另一侧的公司可能只有一个用户。
我对公司表的迁移是
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('address');
$table->string('city');
$table->string('state');
$table->string('contact_person');
$table->string('phone');
$table->string('industry');
$table->string('website');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
我的用户模型是
/**
* Get the posts for the user.
*/
public function companies()
{
return $this->hasOne('App\Company','user_id');
}
我的公司模式是
public function users()
{
return $this->belongsTo('App\User','id');
}
我正在尝试为特定用户获取所有公司
尝试 whereHas 但关系对象中没有数据
$results = Company::whereHas('users', function ($query) {
$query->where('users.id',1);
})->get();
我的错误在哪里?
【问题讨论】: