gpt4 book ai didi

php - Laravel Eloquent 关系不起作用

转载 作者:行者123 更新时间:2023-12-02 03:33:39 25 4
gpt4 key购买 nike

我已经定义了用户与投资组合的关系,但它给了我空,我的用户模型是

class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];

public function portfolio()
{
$this->hasMany('App\Portfolio');
}

}

我的投资组合模型是

class Portfolio extends Model
{

protected $fillable = ['user_id', 'ptitle', 'pdate','pedate','purl','languages','pdes','attachments'];

public function user()
{
$this->belongsTo('App\User');
}
public function attachments()
{
$this->hasMany('App\Attachment');
}
}

并且我已经在迁移上定义了外键,我的迁移代码是

public function up()
{
Schema::create('portfolios', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('ptitle');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}

我再次运行迁移。当我尝试获取用户组合时,它给了我空值,我在 Controller 的顶部声明了这个 use App\User; 然后我通过这个命令找到用户 $user=User::find(1) 最后我做了这个 $user->portfolio() 但它给了我 null 我陷入了 2 到 3 小时请帮助我

最佳答案

您应该返回关系以获取关系数据

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

关于php - Laravel Eloquent 关系不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35963213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com