【问题标题】:convert sql query (join) in laravel query builder在 laravel 查询生成器中转换 sql 查询(连接)
【发布时间】:2020-06-20 12:57:58
【问题描述】:

我想用 laravel 做这个请求(我有 3 张桌子 usersuserprojetprojetsusers hasmany projetsprojet hasmany users 这就是为什么我做另一个表userprojet加入两个表 现在我尝试使用此请求提取特定用户的projet

   select projets.* 
     from projets p 
        , userprojet up 
        , users u 
    where p.id= up.projet_id
      and up.user_id = u.id
      and user_id = 2;

我需要帮助。

【问题讨论】:

  • 你能在你的代码库中添加一个可重现的代码 sn-p 吗?这将帮助其他人确定您当前的解决方案并提供建议和支持。

标签: mysql sql laravel join controller


【解决方案1】:

你可以试试这个:

$users = DB::table('projets')
            ->join('userprojet', 'projet_id.id', '=', 'userprojet.projet_id')
            ->join('userprojet', 'users.id', '=', 'userprojet.user_id')
            ->select('project.*')
            ->where('userprojet.user_id', 2)
            ->get();

参考资料:

Laravel -> Queries -> Joins

【讨论】:

  • 我尝试使用您的解决方案,我在模型中执行这两种方法我返回到项目控制器我这样做:
  • $id = auth()->user()->id; $user = User::find($id);返回 $user->projets();我有这个错误: Illuminate\Database\Eloquent\Relations\BelongsToMany 类的对象无法转换为字符串 {"userId":3,"exception":"[object] (ErrorException(code: 0): Object of class Illuminate\\Database\\Eloquent\\Relations\\BelongsToMany 无法在 C:\\xampp\\htdocs\\gestion-master\\vendor\\symfony\\http-foundation\\Response.php 处转换为字符串:第404章)
【解决方案2】:

您还可以在模型中定义多对多关系,而不是每次都编写查询

// User model
public function projets()
{
    return $this->belongsToMany(Projet::class, 'userprojet');
}

// Projet model
public function users()
{
    return $this->belongsToMany(User::class, 'userprojet');
}

// in controller
$user = User::first(); // for example
dd($user->projets);

// with eager loading
$user = User::with('projets')->first();
dd($user->projets);

【讨论】:

  • 我尝试使用您的解决方案,我在模型中执行这两种方法我返回到项目控制器我这样做:$id = auth()->user()->id; $user = User::find($id);返回 $user->projets();我有这个错误: Illuminate\Database\Eloquent\Relations\BelongsToMany 类的对象无法转换为字符串 {"userId":3,"exception":"[object] (ErrorException(code: 0): Object of class Illuminate\\Database\\Eloquent\\Relations\\BelongsToMany 无法在 C:\\xampp\\htdocs\\gestion-master\\vendor\\symfony\\http-foundation\\Response.php 处转换为字符串:第404章)
  • 首先你不需要通过 auth 用户 id 来查找用户,因为 auth 用户已经是一个用户实例,并且对于错误 - 你会得到一个错误,因为你返回的是查询而不是集合。将return $user->projets(); 更改为return $user->projets;,如示例所示
  • 对不起,因为我花了很多天给你发这个,但是当我使用 $user->projet 未定义属性时我遇到了另一个问题:Illuminate\Pagination\LengthAwarePaginator::$projets {"userId":3, "exception":"[object] (ErrorException(code: 0): Undefined property: Illuminate\\Pagination\\LengthAwarePaginator::$projets at C:\\xampp\\htdocs\\gestion\\app\\Http\\控制器\\API\\ProjetController.php:178)
猜你喜欢
  • 2021-08-07
  • 2015-12-13
  • 2019-10-14
  • 1970-01-01
  • 2017-06-01
  • 2019-09-08
  • 1970-01-01
  • 2020-03-12
  • 2019-03-09
相关资源
最近更新 更多