2017-09-01 74 views
0

我有两个MSSQL表,所以我创建了两个模型[Adress]和[Webshop]。外键是两个表中的Adresse。如何检索Laravel 5.4中的一对一关系数据

1.型号[ADRESS]

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

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

2.型号[网上商店]

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

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

我想作的表与从第一和第二表像webshopID一些数据,手机在[网上商店]表中,并在[地址]表中添加地址。我认为这是两张表格之间的一对一关系。

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 

我想在同一时间检索从这个两个表的数据。这是可能与一个关系,或者我希望使用连接?

编辑: 也许我foreignKeys是错误的

ADRESS表: enter image description here

网上商店表: enter image description here

+0

您的模型都有'protected $ primaryKey ='Adresse';'?看起来有点不可思议,或者是“Adresse”你的默认ID列名?你得到了什么确切的错误? –

+0

详细阐述了表格架构 –

+0

其默认的id列名称。一个int作为主键。我没有得到任何错误,我等了2-3分钟,然后什么也没有。 –

回答

0

尝试Address模型来改变你的关系

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

Webshop模型

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

编辑

我们检索的关系,你可以做

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

与限制命令App \ Adress :: where('webshop) - >限制(10) - > get()'工作。当我使用这个命令'App \ Adress :: where('webshop) - > get()'tinkes冻结2-3min并且什么也不做,没有错误没有结果只是一个新的行,我可以把我的命令放在cmd中 –

+0

I认为你应该阅读Laravel文档。您不能在关系中创建'where'子句,而是使用['whereHas()'](https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence)方法。检查我的和编辑 – Desh901

+0

然后,您正在定义一对一的关系。 'App \ Address :: find($ id) - > webshop'将只返回一个元素 – Desh901

0

请这个尝试 -

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(); 

希望这将帮助你。