没有从Eloquent RelationShip Laravel 5.1上的查询中获取正确的模型记录

时间:2016-04-13 19:22:10

标签: php laravel eloquent

我正在开发5.1 Laravel应用程序。在那个应用程序中,我在商务模型(西班牙语名为Negocio)和用户模型之间有一个OnetoMany关系。当我注册我的用户时,我创建一个令牌并将其保存在users表中,以便在电子邮件混淆中使用该令牌....

当用户确认帐户时,我想使用控制器收到的令牌创建一个目录,其中包含用户与'public / negocios /'相关的商家名称。

所以在我的控制器中使用userconfirmartion我有:

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

谢谢你们......很抱歉这篇长篇文章。

2 个答案:

答案 0 :(得分:0)

这是一个不同的逻辑,但可能有所帮助:

//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)

答案 1 :(得分:0)

进一步阅读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上构建查询的新技巧。