假設您有另一個模型用戶名爲users
。你可以有addresses
和users
如下之間定義的關係,
public function up()
{
Schema::create('addresses', function(Blueprint $table)
{
$table->increments('id');
$table->string('add1');
$table->string('add2');
$table->string('city');
$table->string('contact_no');
$table->enum('is_primary',['yes','no'])->default('no');
$table->integer('user_id')->unsigned();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
在用戶模型類,
class User extends Model {
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'users';
public function addresses()
{
return $this->hasMany('App\Address');
}
}
在Address類
class Address extends Model {
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'addresses';
public function user()
{
return $this->belongsTo('App\User');
}
}
有關創建表的更多詳細信息,可以發現關於Laravel的官方Schema Docs。而關於關聯船here
UPDATE
根據this問題的更多信息,你必須先引用表之前創建引用表。在我們的情況下,在運行遷移以創建addresses
表之前,必須存在users
。
簡單的用例
假設,在控制你想要找出多少地址特定用戶,那麼你可以做以下,
$addressCount = User::find($userId)->addresses->count();
請注意相關的模型而User::find($userId)->addresses
返回集合類型User::find($userId)->addresses()
返回對象HasMany
你也可以遍歷集合如下,
foreach(User::find($userId)->addresses as $address)
{
echo '<pre>';
print_r($address);
}
在另一邊,你可以得到用戶提供如下特定地址相關聯,
$user = Address:find($addressId)->user; //returns object of type `User`
echo $user->first_name;
以下將不工作
注意,上面Address:find($addressId)->user
不會返回集合,但類User的單個對象。這是因爲belongsTo
關係。
我希望我能爲你明確事情。但沒有官方docs好。
Laracast視頻更適合與Laravel合作。
你能不能解釋一下發生在用戶和地址類?我的意思是,據我所知,功能'adresses'和' user'具有告訴表之間的關係是什麼樣的功能,但是何時調用這些函數? –
我得到一個錯誤150,其引用的FK,我不知道是如果laravel處理遷移的順序,他們創建或評估,如果一個表之前必須存在,因爲fks –
我已更新我的答案解決您的擔憂。 –