2014-03-28 46 views
0

我試圖通過創建消息傳遞應用程序來了解laravel。用戶應該能夠相互發送消息。我使用核心php做了一個類似的應用程序。在laravel 4中定義關係

我完成登錄/認證和遷移,現在停留在定義模型中的關係;

我已經建立3個表使用遷移:

  1. 用戶
  2. 對話
  3. conversations_reply

這是的架構:

  1. 用戶表(對於存儲的細節用戶)

    $table->increments('id'); 
    
    $table->string('username', 50); 
    $table->string('password', 50); 
    $table->string('name', 50);   
    $table->string('email', 254); 
    
    $table->timestamps(); 
    
  2. 對話表(適用於存儲

    $table->increments('id'); 
    
    $table->integer('user_one'); //foreign key of one friend from users table 
    $table->integer('user_two'); //foreign key of second friend from users table 
    $table->string('ip'); 
    
    $table->timestamps(); 
    
  3. conversations_reply表用戶之間的對話)(用於存儲會話文本)

    $table->increments('id'); 
    
    $table->text('reply'); 
    $table->integer('user_id'); 
    $table->integer('conversation_id'); //foreign key of conversations table 
    $table->string('ip'); 
    
    $table->timestamps(); 
    

現在,我試圖在模型中定義關係爲:

  1. User模型預示了的hasManyConversationConversationReply模型關係。
  2. Conversation將有belongsToManyUser模型和的hasManyConversationReply模型關係關係。
  3. ConversationReply模型將有belongsToManyUserConversation模型的關係。

現在我被困在第一個模型(用戶)定義關係,無法繼續進行,因爲我需要定義本地和外鍵,但我無法這樣做,因爲對話表將有2外鍵(2個用戶),我只能定義一個外鍵。

編輯:在對話中應該只有兩個成員,並且兩個用戶應該只有一個對話(如facebook)。他們的新消息應該被添加到他們的舊對話中。在會話表中,ip是開始會話的用戶的ip地址,在conversations_reply表中,ip是用戶的相應ip。

回答

1

在抽象中似乎有點缺陷。您實際上將對話實體的user1和user2設計爲屬性,但它們不是屬性。另外,談話的IP是什麼?

屬性的談話可能的話題,開始時間,結束時間,消息之類的東西的量。

然後一個會話有成員。不完全是兩個,而是很多。所以,你可以只創建一個實體/模型ConversationMembers連接用戶對話

conversation_members表:

$table->increments('id'); 

$table->integer('conversation_id'); 
$table->integer('user_id'); 
$table->string('ip'); 
$table->string('nickname'); 

,改變對話表相應:

$table->increments('id'); 

$table->boolean('public); 
// other attributes you're interested in 
$table->timestamps(); 

現在你可以在你的模型定義的關係:

對話:

public function members() 
{ 
    return $this->hasMany('ConversationMember'); 
} 

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

ConversationMember:

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

public function conversation() 
{ 
    return $this->belongsTo('Conversation'); 
} 

用戶:

public function conversations() 
{ 
    return $this->hasManyThrough('Conversation', 'ConversationMember'); 
} 

public function replies() 
{ 
    return $this->hasMany('ConversationReply'); 
} 

我希望這有助於。

+0

編輯:在對話中應該只有兩個成員,並且兩個用戶應該只有一個對話(如Facebook)。他們的新消息應該被添加到他們的舊對話中。在對話表中,ip是開始對話的用戶的ip地址,在conversations_reply表中,ip是用戶的相應ip – Kanav

+0

@ user170654好吧,它應該是多少成員並不重要,因爲這在數據抽象層面上並不重要。 *許多*表示一個或多個。爲了表明某個用戶已經開始了對話,我認爲決定設置哪個IP不是一個好主意。相反,您應該只添加另一個屬性,如$ table-> boolean('initiator');'到conversation_members表中 - 因爲這實際上是對話成員的屬性。 – Quasdunk