简体   繁体   English

Laravel 4:如何以一对多关系检索数据?

[英]Laravel 4 : How to retrieve data in a one-to-many relationship?

(See codes below) (请参见下面的代码)

I have two models User and Messages. 我有两个模型User和Messages。 I want to take 10 messages- with their associated sender name -based on each of the inputted conversation id and reverse the data. 我想根据每个输入的对话ID接收10条消息及其相关的发件人名称 ,并反转数据。 I have already succeeded in getting the messages but couldn't scale it down to 10 messages each conversation/with their associated sender name. 我已经成功获取了消息,但是每次会话/及其关联的发件人名称都无法将其缩减为10条消息。

  1. I have tried this to return the messages data with the users data but either I don't know how to access the sender's name or it doesn't return the associated user : 我已经尝试过用用户数据返回消息数据,但是我不知道如何访问发件人的名字,或者它不返回相关的用户:

     $allMessages = Messages::with('User')->whereIn('conv_id',$conv_id); 
  2. I have also tried this to return 10 messages but it returns 10 messages based on all the messages it got instead of based on each conversation. 我还尝试过此操作以返回10条消息,但它基于收到的所有消息而不是根据每次对话返回10条消息。

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

How do I get 10 messages based on the id of each conversation together with the messages' associated sender name? 如何根据每个对话的ID以及与消息相关的发件人姓名获得10条消息? Bonus points for improvement of code. 改进代码的奖励点。 Thank you in advance! 先感谢您!


User model 用户模型

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

Messages model 消息模型

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

Controller 控制者

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();
    }

Migrations 移居

Messages table 留言表

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

User table 用户表

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();
        });

EDIT : var_dump preview result of WereWolf's answer in chrome 编辑: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,…}

You may try this: 您可以尝试以下方法:

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

This will return a collection of Messages model so you need to loop like: 这将返回Messages模型的集合,因此您需要像这样循环:

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

Also, you may use: 另外,您可以使用:

// 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;
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)); // dd(json_encode($ heartsPurReport));

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

// in view use foreach loop and use the following for pagination outside foreach loop //在视图中使用foreach循环,并在foreach循环外使用以下命令进行分页

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM