簡體   English   中英

無法從Eloquent RelationShip Laravel 5.1的查詢中獲取正確的模型記錄

[英]Not Getting correct model record from query on Eloquent RelationShip Laravel 5.1

我正在開發5.1 Laravel應用程序。 在該應用程序中,我在商務模型(西班牙語中稱為Negocio)與用戶模型之間具有一對多關系。 當我注冊用戶時,我創建一個令牌並將其保存在用戶表中以在電子郵件確認中使用該令牌。

當用戶確認其帳戶時,我要使用控制器接收的令牌創建目錄,然后在“ public / negocios /”中與該用戶相關的公司名稱。

所以在我的用戶確認控制器中,我有:

public function emailConfirm($token)
{
    try {
        //getting the bussiness that user is related to
        $negocio = App\Negocio::with(['user' => function ($query) use($token) {
            $query->where('token', 'like', $token);
        }])->firstOrFail()->folderProfile();

        //Then we activate the user account
        $user = User::whereToken($token)->firstOrFail()->confirmEmail();
        return redirect('/login')->with('mensaje', '¡Su cuenta de usuario se ha activado, ahora puede iniciar sesión en su cuenta!');

    } catch (ModelNotFoundException $e) {
        return redirect('/login')->with('mensaje', 'Ya se ha confirmado a este usuario, solo inicie sesión ¬¬');
    }
}

在我的業務模型中,我具有創建目錄的功能,該目錄將業務名稱作為目錄名稱:

public function folderProfile()
{
    $name = str_replace(' ', '', $this->nombre_negocio);
    $ruta_a_public = public_path().'/negocios/';
    $ruta_a_public .= $name;
    File::makeDirectory($ruta_a_public, $mode = 0777, true, true);
}

問題是探究php artisan tinker上的代碼Eloquent不僅將與用戶相關的業務記錄在數據庫上,還記錄了我所有的業務記錄。

如果您能告訴我使我的“查詢”按預期工作的最佳方法,將不勝感激

失敗的部分是(基於業務模型):

$negocio = App\Negocio::with(['user' => function ($query) use($token) {
            $query->where('token', 'like', $token);
        }])->firstOrFail()->folderProfile();

我基於我在https://laravel.com/docs/5.1/eloquent-relationships#querying-relations中閱讀的內容

編輯:在我的Negocio模型(西班牙語業務模型)中:

public function user()
{
  return $this->hasMany('App\User', 'negocio', 'codigo_negocio');
}

在用戶模型中,我有這個:

public function negocio()
{
  return $this->belongsTo('App\Negocio', 'negocio', 'codigo_negocio');
}

謝謝大家。對不起,這篇冗長的帖子。

這是一種不同的邏輯,但可能會有所幫助:

//First search for the user
$user = App\User::where('token','like','%' . $token . '%')->first();

//Then search for the business
$negocio = App\Negocio::where('user_id',$user->id)->first();

不要忘記定義表之間的關系。

順便說一句,您在這里忘記了%:

$query->where('token', 'like', '%' . $token . '%');

如果您要查找完全相同的令牌,則應使用以下命令:

Something::where('token',$token)

在進一步閱讀laravel文檔https://laravel.com/docs/5.1/eloquent-relationships之后 ,對我有效並獲得預期記錄的方式是:

$negocio = App\Negocio::whereHas('user', function ($query) use($token) {
            $query->where('token', $token);
        })->firstOrFail()->folderProfile();

這樣,我就能獲得令牌所有者與之相關的正確業務...感謝@szebasztian為我提供了一些有關在雄辯的ORM上構建查詢的新技巧。

暫無
暫無

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

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