Laravel 4中的雄辩调用:在多个表上处理单个列

时间:2013-08-18 14:40:43

标签: php mysql laravel laravel-4 eloquent

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


我有3个表(Users,User_Profiles和User_Answers)。 Users表仅保留用户的基本信息(auto_incremented id,email,password),User_Profiles表包含更多详细信息(图像URL,国家,城市,性别等),并且属于User模型。 User_Answers表是用户给出的答案列表,也属于User模型。


我想要做的是从User_Profiles表中选择所有行,其中city与登录用户的城市相同,在数组中获取他们的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>";
}
?>

2 个答案:

答案 0 :(得分: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,然后循环遍历它们并将它们放入数组中,我不确定你的用户表匹配答案是什么意思...

答案 1 :(得分: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;
}