如何将相关表格的价值与Laravel雄辩集合相结合?

时间:2016-07-16 06:29:22

标签: php mysql laravel eloquent relationships

我有一个表ITEMS(sku,标题)和其他HISTORY(sku,points,startdate)。 表历史记录用作项目点更改的历史记录。

我想在致电

时加入最新的积分
$items = \App\Items::all();

哪种方法最好?

我知道我可以制作自定义属性,但似乎我有太多的查询(因为每个项目都会产生附加查询?)

我也可以建立关系:

public function points()
    {
        return $this->hasOne('App\History','sku','sku')->orderBy('startdate','DESC');
    }

但是有更好的方法吗? BR ÿ

2 个答案:

答案 0 :(得分:2)

由于您只需要最新记录,因此最佳选择是您已展示的<?php if (isset($_POST['submit'])) { include 'dbconnect.php'; for ($i = 0; $i < count($_FILES["photo"]["name"]); $i++) { $target = "img/"; //This is the directory where images will be saved $target_files = $target . basename($_FILES['photo']['name'][$i]); //This gets all the other information from the form $ad_title = $_POST['title']; $ad_price = $_POST['price']; $ad_photo = $target . ($_FILES['photo']['name'][$i]); if (!move_uploaded_file($_FILES['photo']['tmp_name'][$i], $target_files)) { //Tells you if its all ok echo "Sorry, there was a problem uploading your file."; } else { //Gives and error if its not $sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')"; $conn->query($sql); $sql1 = "INSERT INTO images (photos) VALUES ('$ad_photo') "; $conn->query($sql1); //Writes the photo to the server header('location: addconfirm.php'); } } } ?> 关系。这样,关系可以急切加载,因此您只需要调用2个查询,而不是N + 1个查询。

关系:

hasOne

用法:

public function currentPoints()
{
    return $this->hasOne('App\History','sku','sku')->orderBy('startdate','DESC');
}

答案 1 :(得分:0)

例如:

 class Items extends Model
{
    protected $primaryKey = 'sku';

    public function points()
    {
         return $this->hasOne('App\History','sku','sku')->orderBy('startdate','DESC');
    }


    public function getItems(){
         $items = \App\Items::with('points')->get();
    }
}