我正在做一个学习项目。 对拉拉维尔来说很陌生。所以我有一个用户和一个公司简介 CRUD。公司属于用户,用户可能有许多公司。所以在我的用户模型中,我实现了这个
<?php
namespace AppModels;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use AppCompany;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'first_name', 'last_name', 'username', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
//relation with company
public function company(){
return $this->hasMany('AppCompany','id');
}
}
在公司模型中,我做到了
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Company extends Model
{
//table name
protected $table='companies';
//primary keys
protected $primaryKey='id';
//relation with User Model
public function user(){
return $this->belongsTo(AppModelsUser::class);
}
我的公司配置文件控制器是
public function index()
{
//Showing companies under user
$user_id = auth()->user()->id;
$user = User::find($user_id);
$companies=$user->company;
return view('company.profile')->with('companies', $companies);
}
但是在执行方面,似乎
public function user(){
return $this->belongsTo(AppModelsUser::class);
}
公司模型中的此功能不起作用。我的意思是,一家公司被分配给一个用户,但它应该像一个用户中的许多公司一样。我做错了什么?
顺便说一句,我的用户模型位置是应用程序/模型/用户.php,我在身份验证中声明了用户模型路径.php。我的公司.php模型位置是应用/公司.php。请看一看,并尝试帮助这个新手。非常感谢。
我不明白你的问题,但我的答案可能会帮助你
用户属于公司
在模型中用户
public function company()
{
return $this->belongsTo('AppCompany');
}
马比是错误的代码
//relation with company
public function company(){
return $this->hasMany('AppCompany','id'); // not Id foreign_key as company_id
}
这是真的,但你可以把它写得更好
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id)->with('company');
//$companies=$user->company;
return view('company.profile', compact('user');
}