首页 \ 问答 \ Laravel Eloquent查询模型与关系(Laravel Eloquent query model with relationship)

Laravel Eloquent查询模型与关系(Laravel Eloquent query model with relationship)

我有2个模型与公司和DamageReport的关系。

DamageReport始终通过关键company_id链接到公司。

因此,DamageReport中的company_id等于公司中的id。

很简单吧? 现在我的目标是在知道DamageReport的id时查询公司。

例如

我有一行DamageReport表:

id company_id

6  1

ID公司的记录是:

id name

1  Company 1

所以在我的控制器中我有DamageReport id(6)并且需要查询id为1的公司。

我在我的模特中建立了这样的关系

公司型号:

/**
 * The Damage Reprots that belong to the Company.
 */
public function damageReports()
{
    return $this->belongsToMany('App\DamageReport');
}

DamageReport模型:

/**
 * The company of a damagereport
 *
 */
public function company()
{
    return $this->belongsTo('App\Company');
}

现在在我的控制器中我试过这样的事情,但我老实说没有任何线索

$company = new Company;

$company = $company->company($damageReportId);

dd($company);

I have 2 models with a relationship Company and DamageReport.

A DamageReport is always linked to a Company by the key company_id.

So company_id in DamageReport equals id in Company.

Very simple, right? Now my goal is to query the Company when I know the id of the DamageReport.

For example

I have a row of the DamageReport table:

id company_id

6  1

And the record of Company with id is:

id name

1  Company 1

So in my controller I have the DamageReport id (6) and need to query company with id 1.

I've set up a relationship like this in my models

Company model:

/**
 * The Damage Reprots that belong to the Company.
 */
public function damageReports()
{
    return $this->belongsToMany('App\DamageReport');
}

DamageReport model:

/**
 * The company of a damagereport
 *
 */
public function company()
{
    return $this->belongsTo('App\Company');
}

Now in my controller I tried something like this but I honestly have no clue

$company = new Company;

$company = $company->company($damageReportId);

dd($company);

原文:https://stackoverflow.com/questions/46315758
更新时间:2023-01-09 13:01

最满意答案

假设条件是A >=1 & B ==0我们可以使用data.table

library(data.table)
i1 <- setDT(df1)[, grp := rleid(A >= 1 & B==0)][, .I[A >= 1 & B==0 & seq_len(.N)>2], grp]$V1
df1[i1, IncrementalCounter := seq_len(.N)][is.na(IncrementalCounter), 
            IncrementalCounter := 0][, grp := NULL][]   
#    A B IncrementalCounter
# 1: 1 2                  0
# 2: 4 3                  0
# 3: 3 2                  0
# 4: 2 0                  0
# 5: 1 0                  0
# 6: 2 0                  1
# 7: 3 2                  0
# 8: 1 2                  0
# 9: 3 2                  0
#10: 2 0                  0
#11: 2 0                  0
#12: 3 0                  2
#13: 4 0                  3
#14: 2 0                  4
#15: 9 1                  0

我们也可以使用rle来做base R

rl <- with(df1, rle(A >=1 & B ==0))
r2 <- inverse.rle(within.list(rl, {i1 <- which(values)
             lengths[i1-1] <- lengths[i1-1] + 2
             lengths[i1] <- lengths[i1] - 2

         }))

cumsum(r2)*r2
#[1] 0 0 0 0 0 1 0 0 0 0 0 2 3 4 0

数据

df1 <- structure(list(A = c(1L, 4L, 3L, 2L, 1L, 2L, 3L, 1L, 3L, 2L, 
2L, 3L, 4L, 2L, 9L), B = c(2L, 3L, 2L, 0L, 0L, 0L, 2L, 2L, 2L, 
0L, 0L, 0L, 0L, 0L, 1L)), .Names = c("A", "B"), class = "data.frame", 
row.names = c(NA, -15L))

Assuming that the condition is A >=1 & B ==0 we can use data.table

library(data.table)
i1 <- setDT(df1)[, grp := rleid(A >= 1 & B==0)][, .I[A >= 1 & B==0 & seq_len(.N)>2], grp]$V1
df1[i1, IncrementalCounter := seq_len(.N)][is.na(IncrementalCounter), 
            IncrementalCounter := 0][, grp := NULL][]   
#    A B IncrementalCounter
# 1: 1 2                  0
# 2: 4 3                  0
# 3: 3 2                  0
# 4: 2 0                  0
# 5: 1 0                  0
# 6: 2 0                  1
# 7: 3 2                  0
# 8: 1 2                  0
# 9: 3 2                  0
#10: 2 0                  0
#11: 2 0                  0
#12: 3 0                  2
#13: 4 0                  3
#14: 2 0                  4
#15: 9 1                  0

We can also do with base R using rle

rl <- with(df1, rle(A >=1 & B ==0))
r2 <- inverse.rle(within.list(rl, {i1 <- which(values)
             lengths[i1-1] <- lengths[i1-1] + 2
             lengths[i1] <- lengths[i1] - 2

         }))

cumsum(r2)*r2
#[1] 0 0 0 0 0 1 0 0 0 0 0 2 3 4 0

data

df1 <- structure(list(A = c(1L, 4L, 3L, 2L, 1L, 2L, 3L, 1L, 3L, 2L, 
2L, 3L, 4L, 2L, 9L), B = c(2L, 3L, 2L, 0L, 0L, 0L, 2L, 2L, 2L, 
0L, 0L, 0L, 0L, 0L, 1L)), .Names = c("A", "B"), class = "data.frame", 
row.names = c(NA, -15L))

相关问答

更多
  • 您只需要dict中项目的计数,而不是实际项目是locations dict的一部分。 将int与defaultdict一起使用为: locations = defaultdict(int) # makes default value of each key as `0` 并使你for循环为: for item in data['data']: location = item['relationships']['location']['data']['id'] locations[locat ...
  • 尝试以下: //in your loops Try the following: //in your loops
    假设条件是A >=1 & B ==0我们可以使用data.table library(data.table) i1 <- setDT(df1)[, grp := rleid(A >= 1 & B==0)][, .I[A >= 1 & B==0 & seq_len(.N)>2], grp]$V1 df1[i1, IncrementalCounter := seq_len(.N)][is.na(IncrementalCounter), IncrementalCounter := 0][ ...
  • 首先获取所有记录,然后使用如下所示的保存方法修改单个记录: $foos = GanttTask::where('product_id',1)->orderBy('date', 'ASC')->get(); // Get All records $counter = 1; foreach($foos as $foo){ $foo->custom_counter = $counter; $counter +=1; $foo->save(); // Update each record ...
  • UPDATE groups SET lastId = last_insert_id(lastId + 1) 然后你可以得到你的新身份证 SELECT last_insert_id() 在参数中使用last_insert_id将存储该值并在稍后调用时返回。 这种生成自动编号的方法最适合只有几行的MyISAM表(MyISAM始终锁定整个表)。 它还具有在事务处理期间不锁定表的好处(如果它是InnoDB表,将会发生这种情况)。 这是来自MySQL手册 : 如果将expr作为LAST_INSERT_ID()的参 ...
  • 只需在循环中添加一个计数器: $i = 0 Get-ChildItem 'D:\Video\01' -Include $formats -Recurse | ForEach-Object { "{0}*file*{1}" -f $i, $_.Name; $i++ } | Add-Content .\01.dpl 另一种选择是在变量中收集文件列表并使用for循环处理该列表: $files = Get-ChildItem 'D:\Video\01' -Include $formats -Recurse ...
  • 这就是for循环的工作原理: 检查条件,如果持有则转到2,否则终止; 跑身; 执行修改,转到1。 总而言之,你做不到。 另外,如果变量没有进入N + 1 ,循环如何终止? 在这种情况下,循环条件总是成立,因此它将永远运行。 That is how a for loop works: check the condition, if it holds go to 2, else terminate; run body; execute the modification, go to 1. So in a wor ...
  • 柜台是您问题的最佳解决方案吗? 我希望高度分散的系统可能最好没有它们,因此它们被排除在外。 如果您想要计算表中有多少元素。 有一个单独的记录表{counts,TableName,Count},并在添加和删除存储表的事务中使用dirty_update_counter操作。 如果要按特定顺序检索数据(例如,添加它们的顺序),请使用此处显示的OrderedBy解决方案。 如果你想要快速的外键查找,我会考虑使用你的键的类型(item_id的二进制值可能更快)并测试你是否有任何重大改进。 另外,我不明白为什么在删除表 ...
  • 在onCreate()你在UI线程内部开始一个无限循环,完全阻止它。 或者,您可以使用Handler进行定期更新。 也许使用更大的延迟并在某个时间停止。 public class MainActivity extends AppCompatActivity implements Runnable { private final Handler mHandler = new Handler(); @Override protected void onCreate(Bundle sav ...
  • select Enrolid,Dtstart,"Preceding Dtend" ,count(case when Dtstart - "Preceding Dtend" > 31 then 1 end) over ( partition by Enrolid order by Dtstart rows unbounded p ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。