简体   繁体   English

如何在 Laravel 5.4 中从一对一关系中检索数据

[英]How to retrieve data from one to one relationship in Laravel 5.4

I have two MSSQL tables so i created two models [Adress] and [Webshop].我有两个 MSSQL 表,所以我创建了两个模型 [Adress] 和 [Webshop]。 The foreign key is Adresse in both tables.两个表中的外键都是 Adresse。

1.Model [Adress] 1.型号【地址】

class Adress extends Model
{
    protected $table = "Adress";
    protected $primaryKey = 'Adresse';
    public $timestamps = false;

    public function webshop()
    {
        return $this->hasOne('App\Webshop', 'Adresse');
    }
}

2.Model [WebShop] 2.型号【网店】

class Webshop extends Model
{
    protected $table = "Webshop";
    protected $primaryKey = 'Adresse';
    public $timestamps = false;

    public function adress()
    {
        return $this->belongsTo('App\Adress','Adresse');
    }
}

I would like to make a table with some data from the first and second table like the webshopID, mobile is in [Webshop] table and adress in the [Adress] table.我想用第一个和第二个表中的一些数据制作一个表,比如 webshopID,移动设备在 [Webshop] 表中,地址在 [Adress] 表中。 I think this is a one to one relationship between this two tables.我认为这是这两个表之间的一对一关系。

in php artisan tinker :php artisan tinker

App\Adress::all();          -> this is working 
App\Adress::find(2910)->webshop  -> this is also working
App\Adress::with('webshop')->get() -> this is NOT working

I would like to retrieve data from this two tables at the same time.我想同时从这两个表中检索数据。 Is this possible with a relationship or do i heave to use the joins?这可能与关系有关还是我不得不使用连接?

EDIT: maybe my foreignKeys are wrong编辑:也许我的外键是错误的

Adress table:地址表: 在此处输入图片说明

Webshop table:网店表: 在此处输入图片说明

Please try with this -请试试这个 -

use App\Adress;
use App\Webshop;

$result = Webshop::with('Adress')->where('Webshop.id',$id)->get();
or
$result = Adress::with('Webshop')->where('Adress.id',$id)->get();

Hope this will help you.希望这会帮助你。

Try to change your relationship in Address model to尝试将Address模型中的关系更改为

$this->hasOne('App\Webshop', 'Adresse', 'Adresse');

and in Webshop model并在Webshop模型中

$this->belongsTo('App\Address', 'Adresse', 'Adresse');

EDIT编辑

Now to retrieve the relationships you can do现在检索你可以做的关系

$webshop = App\Address::find($id)->webshop;
$address = App\Webshop::find($id)->address

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM