【问题标题】:Laravel 4 : How to retrieve data in a one-to-many relationship?Laravel 4:如何以一对多的关系检索数据?
【发布时间】:2014-08-11 20:26:04
【问题描述】:

(见下面的代码)

我有两个模型用户和消息。我想根据每个输入的对话 ID 获取 10 条消息-及其关联的发件人姓名并反转数据。我已经成功地收到了这些消息,但无法将每个对话/及其关联的发件人姓名缩减到 10 条消息。

  1. 我已经尝试用用户数据返回消息数据,但要么我不知道如何访问发件人的姓名,要么它不返回关联的用户:

    $allMessages = Messages::with('User')->whereIn('conv_id',$conv_id);
    
  2. 我也尝试过返回 10 条消息,但它会根据收到的所有消息而不是每次对话返回 10 条消息。

    $allMessages = Messages::whereIn('conv_id',$conv_id)->take(10);
    

如何根据每个对话的 ID 以及消息的关联发件人姓名获取 10 条消息?改进代码的奖励积分。提前谢谢!


用户模型

public function messages(){
    return $this->hasMany('Messages');
}

消息模型

public function user(){
    return $this->belongsTo('User');
}

控制器

public function index()
    {
        $timestamps = Input::get('from'); //timestamp of latest message
        $conv_id = Input::get('conv_id'); //array of conversation ids
        $allMessages = Messages::whereIn('conv_id',$conv_id);
        if(is_null($timestamps)){
           $messages = $allMessages->orderBy('created_at','desc');
        }else{
           asort($timestamps);
           $messages = $allMessages->where('created_at','>',end($timestamps));
        }
        return $messages->get()->reverse();
    }

迁移

消息表

Schema::create('messages', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('conv_id');
            $table->text('body');
            $table->timestamps();
        });

用户表

Schema::create('users',function($table)
        {
            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password',100);
            $table->string('name',150);
            $table->string('usertype',50);
            $table->boolean('block');
            $table->string('remember_token',100);
            $table->timestamp('lastlogin_at');
            $table->timestamps();
            $table->softDeletes();
        });

编辑:在 chrome 中 WereWolf 的答案的 var_dump 预览结果

0: {id:37, user_id:1, conv_id:2, body:damn mate, created_at:2014-06-20 00:55:32,…}
1: {id:38, user_id:1, conv_id:2, body:hello, created_at:2014-06-20 02:18:21,…}
2: {id:39, user_id:1, conv_id:2, body:dude, created_at:2014-06-20 02:20:10,…}
3: {id:40, user_id:1, conv_id:2, body:test, created_at:2014-06-20 06:52:37,…}
4: {id:67, user_id:1, conv_id:2, body:haha, created_at:2014-06-21 01:25:56,…}
5: {id:68, user_id:1, conv_id:2, body:hey, created_at:2014-06-21 01:26:14, updated_at:2014-06-21 01:26:14,…}
6: {id:69, user_id:1, conv_id:1, body:testa, created_at:2014-06-21 01:27:02,…}
7: {id:70, user_id:1, conv_id:1, body:testser, created_at:2014-06-21 01:27:32,…}
8: {id:115, user_id:1, conv_id:2, body:haha, created_at:2014-06-21 02:45:06,…}
9: {id:116, user_id:1, conv_id:2, body:test, created_at:2014-06-21 02:57:03,…}

【问题讨论】:

    标签: php laravel laravel-4 eloquent one-to-many


    【解决方案1】:

    你可以试试这个:

    $allMessages = Messages::with('user')
                           ->where('conv_id', $conv_id)
                           ->take(10)
                           ->get();
    

    这将返回Messages 模型的集合,因此您需要像这样循环:

    @foreach($allMessages as $message)
        {{ $message->user->name }}
        {{ $message->body }}
    @endforeach
    

    另外,你可以使用:

    // Get the first message and then user->name
    $allMessages->first()->user->name;
    
    // Get the second message and then user->name
    $allMessages->get(1)->user->name;
    

    【讨论】:

    • 我如何访问用户名?我似乎在 var_dump 对象中找不到它。
    • $allMessages->first()->user->name
    • 谢谢!顺便说一句,我注意到你使用了 where() 而不是 whereIn()。这是一个错字还是我真的应该在哪里使用?顺便说一句,我的 conv_id 是一组对话 ID。
    • 你应该使用where
    • 如果$conv_id是多个conv_ids的数组,那么你应该使用whereIn,否则使用where,欢迎:-)
    【解决方案2】:
    public function PurchaseReport () {
    
                $heartsPurReport = DB::table('users')
    
                            ->join('heartz_payment', 'users.id', '=', 'heartz_payment.user_id')
                            ->join('heartz_transaction', 'users.id', '=', 'heartz_transaction.user_id')
                            ->select('users.username', 'users.email', 'heartz_payment.heartz', 'heartz_payment.transaction_id', 'heartz_payment.order_id', 'heartz_payment.created_at', 'heartz_payment.status',  'heartz_payment.amount', 'heartz_transaction.event')->paginate(20);
    

    //dd(json_encode($heartsPurReport));

                            return view('Reports.Heartz.Purchase')->with('heartz',  $heartsPurReport);                          
        }
    

    // 在视图中使用 foreach 循环并在 foreach 循环外使用以下分页

                           {!! $consumption->render() !!}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 2017-01-17
      • 2013-09-14
      • 2014-04-18
      • 2021-04-06
      • 2023-02-07
      • 1970-01-01
      相关资源
      最近更新 更多