如何使用laravel中的外键引用单个表来获取两个记录

问题描述 投票:0回答:2

我是Laravel的初学者。我试图根据外键显示所有表记录。我面临的问题是我的Travel_offering表有两列beginning_location和Ending_location都是引用到位置表的外键我想要检索两个记录。我知道关系,即属于并且有很多。但我无法为引用单个表的多个列执行此操作

travel_offerings表

class CreateTravelOfferingsTable extends Migration
{
    public function up()
    {
        Schema::create('travel_offerings', function (Blueprint $table) {

            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('begning_location')->unsigned();
            $table->integer('dest_location')->unsigned();
            $table->time('leaving_time');
            $table->date('leaving_date');
            $table->float('offering_price');
            $table->boolean('active');
            $table->timestamps();

        });

        Schema::table('travel_offerings',function (Blueprint $table){

            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('begning_location')->references('id')->on('locations');
            $table->foreign('dest_location')->references('id')->on('locations');

        });

    }

    public function down()
    {
        Schema::dropIfExists('travel_offerings');
    }

}

位置表

class CreateLocationsTable extends Migration
{
    public function up()
    {
        Schema::create('locations', function (Blueprint $table) {
            $table->increments('id');
            $table->string('location_spot');
            $table->string('location_town');
            $table->string('location_city');
            $table->float('location_latitude');
            $table->float('location_longitude');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('locations');
    }
}

地点模型

class locations extends Model
{
    function location()
    {
        //what should I write here

    }
}
php laravel laravel-5
2个回答
0
投票

您必须为每个关系创建两个关系。然后你可以通过说:Location::with('dist1','dist2')->get()来获取它们


0
投票

您必须将位置关系模型与locations.php中的另一个模型编写,例如,如果您的位置模型与TravelOffering模型具有一对一关系,则您的模型文件应该像

class locations extends Model
{
    function travel_offering ()
    {
        return $this->hasOne('App\TravelOffering','foreign_key', 'local_key');
    }
}

您可以在此处定义多个关系。看看laravel关系documentation。通过定义关系,您可以根据关系来检索值,这意味着您不再需要编写嵌套查询。如果您拥有雄辩的位置结果集模型,您也可以获得TravelOffering。

$a = locations::find(1);
$TravelOffering = $a->travel_offering;

*您应该使用大写单数字命名模型,外键与parent_table_name_id一样,因为Eloquent根据模型名称确定关系的外键。如果这样做,则不必指定相关的外键

© www.soinside.com 2019 - 2024. All rights reserved.