0

我又回来了另一个 Laravel 问题,我似乎无法用我的程序 PHP,直接 mysql_query 背景来破解。它基本上涉及多个表的 Eloquent ORM。


我有 3 个表(Users、User_Profiles 和 User_Answers)。Users 表只保留用户的基本信息(auto_incremented id、电子邮件、密码),User_Profiles 表包含更多详细信息(图片 url、国家、城市、性别等)和属于 User 模型。User_Answers 表是用户给出的答案列表,也是属于 User 模型的。


我想做的是从 User_Profiles 表中选择所有行,其中城市与登录用户的城市相同,在数组中获取他们的 user_id,然后将答案(来自 User_Answers 表)与答案进行比较当前登录的用户。以下是我想要做的,但使用纯 PHP 和(仅用于解释目的)mysql_query。我提前为糟糕的代码道歉。我只需要指出正确的方向。

<?php

$link = mysql_connect("localhost", "xxx", "xxx");
$db = mysql_select_db('testersize', $link);

$id = 2;
$sql = "SELECT city FROM user_profiles WHERE user_id = $id";
$query = mysql_query($sql, $link);

$row = mysql_fetch_row($query);

$city = $row[0];

echo $city . "</br>";

$sql = "SELECT user_id FROM user_profiles WHERE city = '$city'";
$matches = mysql_query($sql, $link);

//

while($row = mysql_fetch_row($matches)){
  $u_id = $row[0];
  $sql = "SELECT books, movies, music FROM user_answers WHERE user_id = $u_id";
  $query2 = mysql_query($sql, $link);
  $row2 = mysql_fetch_row($query2);
  echo "<h2>User Number: " . $u_id . "</h2>";
  echo "your favorite books:" . $row2[0] . "</br>";
  echo "your favorite movies:" . $row2[1] . "</br>";
  echo "your favorite music:" . $row2[2] . "</br>";
}
?>
4

2 回答 2

0
$user_ids = User_Profiles::where('city','=',Auth::user()->city)->lists('user_id');
$favorites = User_Answers::whereIn('user_id',$user_ids)->get();
foreach($favorites as $favorite)
{
    echo $favorite->book;
    echo $favorite->music;
    echo $favorite->movie;
}
于 2013-08-19T12:28:20.223 回答
0
$user_profiles = User_Profiles::where('city','=',Auth::user()->city)->get();
foreach($user_profiles as $user_profile){
  $id = array('user_id'=>$user_profile->user_id);
}

因此,该代码将按城市为您获取 user_profiles,然后遍历它们并将它们放入一个数组中,我不确定您所说的匹配用户表的答案是什么意思..

于 2013-08-18T16:50:04.360 回答