我试图将Jeffrey Way的多对多关系教程应用到我的私人消息应用程序中,但是我被卡住了。我试图获得与用户关联的2个对话,haha
和hehe
。然而,Laravel给我的错误:Laravel 4.2多对多的关系:无法从数据透视表中读取
Column not found: 1054 Unknown column 'Conversations.user_id' in 'where clause' (SQL: select * from `Conversations` where `Conversations`.`user_id` = 1)
我有我的谈话表中的这些数据:
+---------+----------+
| conv_id | name |
+---------+----------+
| 1 | haha |
| 2 | hehe |
+---------+----------+
在我user_conversations表:
+----+-------------+--------+
| id | conv_id | user_id|
+----+-------------+--------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
+----+-------------+--------+
1.我已经试过: In controllers:
用户:return $this->belongsToMany('User','id');
Conversatons:return $this->hasMany('Conversations','conv_id');
,但我得到的结果是:haha
而不是haha
和hehe
2.我也试过:
用户:return $this->belongsToMany('User','user_conversations');
Conversatons:return $this->hasMany('Conversations','user_conversations');
但laravel回到我下面的错误:
Column not found: 1054 Unknown column 'Conversations.user_conversations' in 'where clause' (SQL: select * from `Conversations` where `Conversations`.`user_conversations` = 1)
我仍然在Laravel相对较新,所以我可能会犯一些愚蠢的错误。
这里是我的代码:
模型
对话
class Conversations extends Eloquent {
protected $table = 'Conversations';
protected $fillable = array('name');
public function users(){
return $this->belongsToMany('User');
}
}
用户
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
....
public function conversations(){
return $this->hasMany('Conversations');
}
}
个
CONTROLLERS
会话控制器
public function create()
{
$loginuser = User::find(Auth::user()->id);
$conversations = $loginuser->conversations;
return View::make('msgsystem.Conversations.Conversations',array('conversations'=>$conversations));
}
MIGRATIONS(在功能上())
用户
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();
});
个
对话
Schema::create('Conversations', function(Blueprint $table)
{
$table->increments('conv_id')->index();
$table->string('name',100);
$table->timestamps();
});
改进的代码user_conversations
Schema::create('user_conversations', function(Blueprint $table)
{
$table->increments('id')->unsigned();
$table->integer('conversation_id')->unsigned()->index();
$table->foreign('conversation_id')->references('conv_id')->on('conversations')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
奖励积分。非常感谢你!
如果您尝试实施的是多对多关系,则您的用户和对话模型应该是belongsToMany。 – Jeemusu
@Jeemusu是的,你说得对。我正要回答我的问题,因为我最近发现了这个问题,当我再次查看Way先生的教程时。也许你可以回答它,并进一步解释为什么hasMany-belongsToMany不具有多对多的关系?谢谢! – Mark