簡體   English   中英

Laravel雄辯的關系不起作用

[英]Laravel Eloquent Relation not working

我已經定義了與投資組合的用戶關系,但是它給了我空的用戶模型

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');
        });
    }

我再次運行遷移。 當我嘗試獲取用戶投資組合時,它為我提供了空值,我在控制器頂部use App\\User;聲明了此值use App\\User; 然后我通過此命令$user=User::find(1) ,最后我做了這個$user->portfolio()但是它給了我null我被困在2到3個小時內,請幫助我

您應該返回關系以獲取關系數據

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

基本的簡化示例設置(在以下示例中使用):

class User extends Model {
    public function portfolio()
    {
        //you missed the return
        return $this->hasMany('App\Portfolio');
    }

}
class Portfolio extends Model {
    public function user()
    {
        //you missed the return
        return $this->belongsTo('App\User');
    }
}

假設您有一個ID為1的用戶和一個相關的投資組合條目:

$mUser = User::findOrFail(1); //Return User model
$mUserLazy = User::with('portfolio')->findOrFail(1); //Preload portfolio

$mPortfolioQueryBuilder = $mUser->portfolio(); //QueryBuilder

$aPortfolio = $mUser->portfolio; //Portfolio Collection
$aPortfolio = $mUserLazy->portfolio; //Portfolio Collection
$aPortfolio = $mPortfolioQueryBuilder->get(); //Portfolio Collection

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM