Laravel查询构建器

时间:2014-04-04 11:35:35

标签: laravel laravel-4

我是Laravel的新手。任何人都可以告诉我应该如何在laravel查询构建器中编写此查询?

SELECT users.id, customers.zip
FROM users, customers
WHERE users.id =26
AND customers.customer_id = users.user_name

4 个答案:

答案 0 :(得分:1)

最简单的方法是使用查询构建器 - here's a link to a join example

当您开发Laravel知识时,您可能会开始使用Laravel的Eloquent ORM,在这种情况下,您需要read this section of the docs来学习如何定义表之间的关系。

更新

我在上面看到你的评论,关于无法理解文档。这是令人惊讶的,因为他们在这方面经过了充分的测试和清晰,但我认为你在寻找答案:

DB::table('users')
    ->where('users.id', '=', 26)
    ->join('customers', 'customers.customer_id', '=', 'users.user_name')
    ->select('users.id', 'customers.zip');

答案 1 :(得分:0)

那么在你的情况下最好使用HasOne关系http://laravel.com/docs/eloquent#relationships 您需要创建Customer类

 class Customer extends Eloquent {

   //if you table is not called customers you need to add
    protected $table = 'table_name';

    }

比用户控制器

class User extends Eloquent {

        public function customers()
        {
            return $this->hasOne('Customer', 'customer_id');
        }

    }

简而言之,laravel会找到users.id(26)并使用customer_id(26)加入它们,它在控制器中的代码更简单,更简单。

$user_id = 26; 
$user = User::find($user_id);

echo "username:".$user->user_name."user/customer zip code: ".$user->customers->zip;

这种关系只有当每个用户在customers表中都有一条记录时(如果你有两条user_id 26它只会获得第一条),如果你想让它们多于一条记录,你需要使用的每个用户hasMany

答案 2 :(得分:0)

DB::table('users')
->join('customers','users.username', '=', 'customer.customer_id')
->select('users.id', 'customer.zip')
->where('users.id','=', '26')
->get();

这将适合你。

请参阅此内容以获取更多https://laravel.com/docs/5.2/queries

如果您想使用雄辩的收藏品,请参阅此处 https://laravel.com/docs/5.2/collections#method-filter

答案 3 :(得分:0)

<块引用>

DB::table('users as u1') ->join('customers as c1', 'c1.customer_id', '=', 'u1.user_name') ->->where('users.id', '=', 26) ->select('users.id', 'customers.zip');