Laravel:每张桌子都需要一个模型吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24376908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:41:31  来源:igfitidea点击:

Laravel: Does every table need a model?

phplaravelmodellaravel-4eloquent

提问by user3527894

I am building an occasion system with Laravel. I have several tables like:

我正在用 Laravel 构建一个场合系统。我有几个表,如:

  • occasions
  • occasion_categories (cars, trikes and other)
  • 场合
  • 场合_类别(汽车、三轮车和其他)

Now i have a model called Occasionwhich represents the table occasions, it also has a foreign key to the occasion_categories table.

现在我有一个模型Occasion,它代表表场合,它还有一个到场合_类别表的外键。

I want to retrieve all occasion categories, but

我想检索所有场合类别,但是

  • do i need to make a seperated model called OccasionCategoryfor the occasion_categories and define all relations in these models,

  • or can i just make a method in the Occasionclass like getCategories()and then use the DBclass like DB::table('occasion_categories')->get()to retrieve all possible categories?

  • 我是否需要创建一个单独的模型来调用OccasionCategoryoccurrence_categories 并定义这些模型中的所有关系,

  • 或者我可以在Occasion类中创建一个方法getCategories(),然后使用DBDB::table('occasion_categories')->get()来检索所有可能的类别?

回答by The Alpha

Updated on 4th Oct, 2019:

2019 年 10 月 4 日更新:

In short, NO, you can use Query Builderinstead of Eloquent ORMbut if you want to use Eloquent ORMthen each table has to be bound to a model. Also, a model is not necessarily has to be an Eloquent model, you can create a model without extending eloquent model which may or may not use database. A model doesn't mean a database access layer but... anyways, it's another big topic.

简而言之,NO, 你可以使用Query Builder而不是Eloquent ORM但是如果你想使用Eloquent ORM那么每个表都必须绑定到一个model. 此外,模型不一定必须是Eloquent model,您可以在不扩展 eloquent 模型的情况下创建模型,该模型可能会或可能不会使用数据库。模型并不意味着数据库访问层,但是……无论如何,这是另一个大话题。

Original Answer:

原答案:

Actually you need to create two Eloquentmodels for both of your tables if you are using Eloquent, for example:

实际上Eloquent,如果您正在使用Eloquent,则需要为两个表创建两个模型,例如:

class Occasion extend Eloquent {
    // Laravel will look for occasions table for Occasion model so following line
    // is optional if you don't want to use another table name for Occation model
    protected $table = 'occasions';

    // Now declare the relationship with "occasion_categories" table
    public function occasionCategory()
    {
        // Make sure you have used occasion_categories_id as the foreugn key
        return $this->belongsTo('OccasionCategory', 'occasion_categories_id', 'id');
    }
}

Now create the OccasionCategorymodel:

现在创建OccasionCategory模型:

class OccasionCategory extend Eloquent {

    protected $table = 'occasion_categories';

    // Now declare the relationship with "occasion_categories" table
    public function occasions()
    {
        // Make sure you have used occasion_categories_id as the foreign key
        return $this->hasMany('Occasion', 'occasion_categories_id', 'id');
    }
}

Now you may retrieve the occasions with it's parent occasions_category using something like this:

现在你可以使用这样的方法检索它的父事例_category 的场合:

// Use the Occasion model
$allOccasionsWithCategory = Occasion::with('occasionCategory')->get();

// Find one Occasion whose id is 1 with OccasionCategory
$oneOccasionsWithCategory = Occasion::with('occasionCategory')->find(1);

// You may use this to get the related occasionCategory model
$occasionCategory = $oneOccasionsWithCategory->occasionCategory;

// Use the OccasionCategory model
$allOccasionsWithCategory = OccasionCategory::with('occasions')->get();

// Find one OccasionCategory whose id is 1 with Occasion
$oneOccasionsWithCategory = OccasionCategory::with('occasions')->find(1);

// You may use this to get all the related occasions model
$occasions = $oneOccasionsWithCategory->occasions;

Read more about relationshipon Laravelwebsite.

在网站上阅读更多关于关系Laravel信息。

If you use Query Builderdirectly then you may use something like this (without a model):

如果你Query Builder直接使用,那么你可以使用这样的东西(没有模型):

// All occations
$occations = DB::table('occations')->get();

// All occasions and related occasion_categories
$occationsAndCategories = DB::table('occations')
                            ->join('occasion_categories', 'occasions.occasion_category_id', '=', 'occasion_categories.id')
                            ->get();

Read more about Query Builderon Laravelwebsite.

在网站上阅读有关查询生成器的更多信息Laravel

回答by menjaraz

The laravelish way to do database is using the Query Builderor Eloquent: Laravelis a framework and it always makes sense to leverage the resources it exposes.

该laravelish方式做数据库使用的是查询生成器机锋Laravel是一个框架,它总是有道理利用它暴露的资源。



Laravel: Does every table need a model?

Laravel:每张桌子都需要一个模型吗?

The short answer:

简短的回答:

  • No, it doesn't as long as you don't use Eloquent.
  • 不,只要您不使用Eloquent就不会 。

The long answer:

长答案:

  • The Query Builderis the way to go if you still want to stick to laravel convention.

  • You may also use the plain old PDO: Remember Laravel is a actually a PHP framework!

  • 查询生成器是去,如果你仍然要坚持laravel约定的方式。

  • 您也可以使用普通的旧PDO:记住 Laravel 实际上是一个 PHP 框架!



My take:

我的看法:

It's always rewarding to be consistent:

保持一致总是有益的:

  • Do it the Eloquentways (Models + relationships definition) despite you can mix Eloquentand some Query Builderas you suggested.

  • Doing it using Query Builderexclusively is also consistent and possible.

  • 做到这一点的Eloquent方法(模型+关系定义),尽管你可以混合Eloquent和一些Query Builder如你所说。

  • 完全使用Query Builder它也是一致的和可能的。

My personal preference goes to the Eloquentoption.

我的个人偏好是Eloquent选项。



Solution:

解决方案:

WereWolf - The Alphaanswerprovides excellent possible solutions using both options.

WereWolf - Alpha答案提供了使用这两种选项的极好可能的解决方案。

回答by DevBodin

Just wanted to chime in here with an update.

只是想在这里提供更新。

In this particular instance, I'm not sure things have changed since this was posted (could be wrong, always more to discover), but in the case of Many-to-Many relationships, the one-to-one relationship between table and model is broken, thanks to the pivot()method .

在这个特定的例子中,我不确定自从发布后事情是否发生了变化(可能是错误的,总是有更多的发现),但在多对多关系的情况下,表和表之间的一对一关系由于pivot()方法,模型已损坏。

Taking from one of my own projects:

从我自己的一个项目中获取:

public function fees()
{
    return $this->belongsToMany(Service::class)->withPivot("description");
}

In this way, you can have two models ("Fee" and "Service"), but you can access data on the intermediary table without needing a "ServiceFee" model.

通过这种方式,您可以拥有两个模型(“Fee”和“Service”),但是您可以访问中间表上的数据,而无需“ServiceFee”模型。

In Blade:

在刀片中:

{{ $service->pivot->description }}

At a glance, this may seem trivial, but get enough many-to-many relationships going and the number tables could even surpass the number of models. (Whether this hypothetical scenario is necessarily well-designed is a matter I am sadly lacking the time to ponder.)

乍一看,这可能看起来微不足道,但获得足够多的多对多关系,数字表甚至可以超过模型的数量。(这个假设场景是否一定是精心设计的,我很遗憾没有时间去思考。)

回答by Kenyon

Although I am not positive, I am pretty sure that would work. Or, DB::raw('select * from occasion_categories')should work.

虽然我并不乐观,但我很确定这会奏效。或者,DB::raw('select * from occasion_categories')应该工作。

I don't know what the best practices here are, but if you're simply asking if it's possible then yes. One of those two methods should work just fine.

我不知道这里的最佳实践是什么,但如果你只是问是否可能,那么是的。这两种方法之一应该可以正常工作。