天天看點

3分鐘短文:說說Laravel模型中還算常用的2個“關系”

引言

上一章我們介紹了比較簡單的laravel模型關聯關系中的一對一,介紹了關聯操作方法。

太難的概念了解起來都費勁,更不用說寫代碼了,是以對于太難的那些關聯關系,

且不論其效率如何,我們都不先做介紹。

3分鐘短文:說說Laravel模型中還算常用的2個“關系”

本期說一說2個比較常用的關聯模型。

belongsTo 關系

正好像對于一個詞語,找到對應的反義詞,或者說有一個圖檔,找到其鏡像圖檔這樣的。

有作用力,就有反作用力。一對一關系模型中,A有一個B,則反過來,B屬于一個A。

這就是首先要介紹的 belongsTo 關系。

在模型Profile中添加對應到User模型的關系:

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

也就是說,有一個profile是從屬于user的,這與User模型的hasOne正好是對應關系。

在代碼中使用該關聯關系:

$email = Profile::where('id', 3)->first()->user->email;           

其中first方法傳回一個Profile模型對象執行個體,在Profile類中我們聲明了 user() 方法用于關系使用者模型,

是以此處鍊式調用 user 屬性,傳回的是一個 AppUser 對象執行個體,其包含 User 模型的所有屬性,

是以 email 屬性也相應傳回資料庫内的字段值。

一對多關系

還有一個常見的關聯關系是一對多。比如一個使用者有多個手機号,一種狀态包含很多個事件,一個商品有多個标簽等等等等,

這都是一對多的常見用法。

我們使用State模型狀态有多個Event事件這個場景,示範一下一對多關系的聲明,以及應用。在指令行建立模型檔案,同時建立遷移檔案:

php artisan make:model State --migration           

預設在 AppState.php 檔案内生成下面的代碼:

use Illuminate\Database\Eloquent\Model;
class State extends Model {}           

我們還是先去生成資料庫表的遷移檔案,手動實作遷移字段:

public function up()
{
    Schema::create('states', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('name');
        $table->string('abbreviation');
        $table->timestamps();
    });
}           

以及撤回遷移時删除表:

public function down()
{
    Schema::drop('states');
}           

接着在指令行執行遷移指令:

php artisan migrate           

執行成功,資料庫表states就建立成功了。

我們說關聯關系需要外鍵,是以需要手動在events表内追加一個字段 state_id,用于指向剛才建立的表states的id字段。

執行指令行,建立遷移檔案:

php artisan make:migration add_state_id_to_events_table --table=events           

手動實作遷移檔案的修改:

public function up()
{
    Schema::table('events', function (Blueprint $table) {
        $table->integer('state_id')->unsigned()->nullable();
        $table->foreign('state_id')->references('id')->on('states');
    });
}           

以及復原遷移時手動删除追加的字段:

public function down()
{
    Schema::table('events', function (Blueprint $table) {
        $table->dropForeign('events_state_id_foreign');
        $table->dropColumn('state_id');
    });
}           

基礎資料準備完畢,下面在模型内添加關聯關系:

class State extends Model {
    public function events() {
        return $this->hasMany('App\Event');
    }
}           

非常直覺,一種狀态,有若幹個事件。反過來,一個事件,一定屬于某種狀态,那就是belongsTo關系。

class Event extends Model {
    public function state()
    {
        return $this->belongsTo('App\State');
    }
}           

代碼層面也準備好了,下面可以開始使用了。比如建立事件時,手動為其指定狀态:

$event = new Event;
$event->name = "Laravel Hacking and Pizza";
$event->state_id = 41;
$event->save();           

注意,hasMany關聯關系,傳回的是多個模型的集合,可以後續鍊式調用集合的所有方法。

寫在最後

本文不失簡單地介紹了belongsTo和hasMany兩個關聯關系,這在代碼中僅次于hasOne關系,

使用的頻次比較高的。而效率也就是根據外鍵多查詢一次SQL的消耗而已。但是明白其中原理之後,

在代碼内耗時的操作裡,也絕不可濫用關聯關系,否則會嚴重消耗性能。

Happy coding :-)

我是 @程式員小助手 ,專注程式設計知識,圈子動态的IT領域原創作者