Laravel Eloquent:关系的多个外键 [英] Laravel Eloquent: multiple foreign keys for relationship
问题描述
我正在将一个项目移植到 Laravel.
I am in the process of porting a project to Laravel.
我有两个数据库表,它们之间是一对多的关系.它们由三个条件连接.我如何在 Eloquent 中为这种关系建模?
I have two database tables which are in a One-To-Many relationship with each other. They are joined by three conditions. How do I model this relationship in Eloquent?
我不应该修改数据库架构,因为它必须与其他东西保持向后兼容.
I am not supposed to modify the database schema, since it has to remain backwards compatible with other things.
我尝试了以下方法,但不起作用.
I have tried the following, but it doesn't work.
拥有方:
use IlluminateDatabaseEloquentModel;
class Route extends Model
{
public function trips()
{
return $this->hasMany('Trip', 'route_name,source_file', 'route_name,source_file')
}
}
反面:
use IlluminateDatabaseEloquentModel;
class Trip extends Model
{
public function routes()
{
return $this->belongsTo('Route', 'route_name,source_file', 'route_name,source_file');
}
}
示例 Route
数据库值:
id | route_name | source_file
---------------------------------------
1 | Berlin - Paris | file1.xls
2 | Madrid - London| file2.xls
3 | Berlin - Paris | file3.xls
示例 Trip
数据库值:
id | route_name | source_file | duration
---------------------------------------------------------
1 | Berlin - Paris | file1.xls | 78
2 | Madrid - London | file2.xls | 241
3 | Berlin - Paris | file3.xls | 65
1 | Berlin - Paris | file1.xls | 95
1 | Berlin - Paris | file1.xls | 65
Route
和 Trip
有其他属性,为简洁起见我没有在这里包括.
Route
and Trip
have other attributes, which I did not include here for brevity.
这在 Eloquent 中可行吗?
Is this possible in Eloquent?
推荐答案
我不得不处理类似的问题.@fab 提供的解决方案不适用于预加载,因为在处理关系时 $this->source_file 将为 null.我想出了这个解决方案
I had to deal with a similar problem. The solution provided by @fab won't work with eager loading because $this->source_file would be null at the time the relationship is processed. I came up with this solution
安装 Compoships 并在您的模型中对其进行配置后,您可以定义与多个列匹配的关系.
After installing Compoships and configuring it in your models, you can define your relationships matching multiple columns.
拥有方:
use IlluminateDatabaseEloquentModel;
use AwobazComposhipsCompoships;
class Route extends Model
{
use Compoships;
public function trips()
{
return $this->hasMany('Trip', ['id', 'route_name', 'source_file'], ['route_id', 'route_name', 'source_file']);
}
}
反面:
use IlluminateDatabaseEloquentModel;
use AwobazComposhipsCompoships;
class Trip extends Model
{
use Compoships;
public function route()
{
return $this->belongsTo('Route', ['route_id', 'route_name', 'source_file'], ['id', 'route_name', 'source_file']);
}
}
Compoships 支持预先加载.
Compoships supports eager loading.
这篇关于Laravel Eloquent:关系的多个外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!