简体   繁体   English

选择从user_id到user_id的消息

[英]Selecting messages from user_id to user_id

I'm trying to make really simple function user to be able to message to admin only and admin to answer on this message. 我试图使真正简单的功能用户能够仅向管理员发送消息,并由管理员对此消息进行回答。

So far I've made table message with following columns 到目前为止,我已经用以下各列制作了表格message

id | from_id | to_id | subject | message 

In the controller I have this which should select all messages which are sent to current logged in user ( not sure if is correct ) 在控制器中,我应该选择发送给当前登录用户的所有消息(不确定是否正确)

public function index(){
        //$messages = Message::latest()->get();
    $currentUser = Auth::user()->id;
    $messages = Message::
        whereRaw('message.id = (select max(id) from `message` m2 where m2.to_id = '.$currentUser.')' )
        ->orderBy('id', 'desc')
        ->get();        
    return view('test.index', compact('messages'));
}

Now I'm trying to make viewMessage function 现在我正在尝试使viewMessage函数

In index blade this is the link to single message 在索引刀片中,这是单个消息的链接

{!! link_to('test/view/' . $message->from_id, $message->subject) !!}

My Route 我的路线

Route::get('test/view/{id}', 'MessageController@messageView')->name('test.view');

And controller function 和控制器功能

public function messageView($id) {

    $user = User::where('id', $id)->first();

    $messages = $user->messages()->orderBy('created_at', 'asc')->get();
    return View::make('test.view', compact('messages'));
}

When I click on the button I got this error 当我单击按钮时,出现此错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'message.user_id' in 'where clause' (SQL: select * from message where message . user_id = 4 and message . user_id is not null order by created_at asc) SQLSTATE [42S22]:柱未找到:(:SELECT * FROM SQL 1054未知列在'where子句' 'message.user_id' message ,其中messageuser_id = 4和messageuser_id不是由空顺序created_at ASC)

In User model I've added relation to message like: 在用户模型中,我添加了与消息的关系,例如:

public function messages() {
    return $this->hasMany('App\Message');
}

And in Message model 在消息模型中

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

My question why in the query is looking for user_id when on my button I send from_id and how to fix this? 我的问题为什么在我的按钮上发送from_id时在查询中正在寻找user_id以及如何解决这个问题?

Why in the query is looking for user_id 为什么在查询中寻找user_id

You need to add foreign key and ID to the relationship to fix the error, for example: 您需要在该关系中添加外键和ID来修复错误,例如:

public function messages() {
    return $this->hasMany('App\Message', 'from_id', 'id');
}

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

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